-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanageData.php
More file actions
1294 lines (1205 loc) · 60.9 KB
/
manageData.php
File metadata and controls
1294 lines (1205 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
*
* aql - Active Query Listing
*
* Copyright (C) 2018 Kevin Benton - kbcmdba [at] gmail [dot] com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
namespace com\kbcmdba\aql ;
session_start() ;
require( 'vendor/autoload.php' ) ;
require( 'utility.php' ) ;
use com\kbcmdba\aql\Libs\Config ;
use com\kbcmdba\aql\Libs\DBConnection ;
use com\kbcmdba\aql\Libs\Exceptions\ConfigurationException ;
use com\kbcmdba\aql\Libs\Exceptions\DaoException;
use com\kbcmdba\aql\Libs\LDAP ;
use com\kbcmdba\aql\Libs\Tools ;
use com\kbcmdba\aql\Libs\WebPage ;
// ///////////////////////////////////////////////////////////////////////////
function checkIs1or0( $value, $errmsg, &$errors ) {
if ( ( $value !== "1" ) && ( $value !== "0" ) ) {
$errors .= $errmsg . " needs to be 1 or 0 (yes or no) (got $value)<br />\n";
}
}
// ///////////////////////////////////////////////////////////////////////////
function checkIsNumeric( $value, $errmsg, &$errors ) {
if ( ! Tools::isNumeric( $value ) ) {
$errors .= $errmsg . " (got $value)<br />\n";
}
}
// ///////////////////////////////////////////////////////////////////////////
/**
* Get ENUM values from a column definition in the database
* @param mysqli $dbh Database connection handle
* @param string $table Table name
* @param string $column Column name
* @return array Array of ENUM values
*/
function getEnumValues( $dbh, $table, $column ) {
$values = [] ;
// SHOW COLUMNS doesn't support prepared statement parameter binding,
// so we escape the identifiers directly (they come from our code, not user input)
$safeTable = $dbh->real_escape_string( $table ) ;
$safeColumn = $dbh->real_escape_string( $column ) ;
$sql = "SHOW COLUMNS FROM `$safeTable` LIKE '$safeColumn'" ;
$result = $dbh->query( $sql ) ;
if ( $result && ( $row = $result->fetch_assoc() ) ) {
// Type looks like: enum('MySQL','MariaDB','InnoDBCluster',...)
$type = $row['Type'] ;
if ( preg_match( "/^enum\('(.*)'\)$/i", $type, $matches ) ) {
$values = explode( "','", $matches[1] ) ;
}
}
return $values ;
}
// ///////////////////////////////////////////////////////////////////////////
/**
* Verify that AQL can connect to a host and has required permissions
* @param string $hostname Host to connect to
* @param int $port Port number
* @return array ['success' => bool, 'errors' => string[], 'warnings' => string[]]
*/
function verifyHostPermissions( $hostname, $port ) {
$result = [
'success' => true,
'errors' => [],
'warnings' => []
] ;
try {
// Step 1: DNS resolution check
$ip = @gethostbyname( $hostname ) ;
if ( $ip === $hostname && ! filter_var( $hostname, FILTER_VALIDATE_IP ) ) {
$result['success'] = false ;
$result['errors'][] = "DNS resolution failed: Cannot resolve hostname '$hostname'" ;
return $result ;
}
// Step 2: TCP port reachability check (5 second timeout)
$socket = @fsockopen( $hostname, $port, $errno, $errstr, 5 ) ;
if ( ! $socket ) {
$result['success'] = false ;
$errorDetail = '' ;
switch ( $errno ) {
case 110: // Connection timed out
case 10060: // Windows timeout
$errorDetail = "Connection timed out - host may be down or firewall is blocking port $port" ;
break ;
case 111: // Connection refused
case 10061: // Windows connection refused
$errorDetail = "Connection refused - MySQL may not be running on port $port" ;
break ;
case 113: // No route to host
case 10065: // Windows no route
$errorDetail = "No route to host - network path to '$hostname' is unavailable" ;
break ;
default:
$errorDetail = "Cannot reach port $port: $errstr (error $errno)" ;
}
$result['errors'][] = "Network check failed: $errorDetail" ;
return $result ;
}
fclose( $socket ) ;
// Step 3: MySQL connection and privilege checks
$config = new Config() ;
$dbUser = $config->getDbUser() ;
$dbPass = $config->getDbPass() ;
// Try to connect
$mysqli = @new \mysqli( $hostname, $dbUser, $dbPass, '', $port ) ;
if ( $mysqli->connect_error ) {
$result['success'] = false ;
$result['errors'][] = "MySQL connection failed: " . $mysqli->connect_error ;
return $result ;
}
// Check PROCESS privilege (required for SHOW PROCESSLIST)
$processResult = @$mysqli->query( "SHOW PROCESSLIST" ) ;
if ( ! $processResult ) {
$result['success'] = false ;
$result['errors'][] = "PROCESS privilege missing - cannot view queries. Grant with: GRANT PROCESS ON *.* TO '$dbUser'@'%';" ;
} else {
$processResult->close() ;
}
// Check REPLICATION CLIENT privilege (optional, for replica status)
$replResult = @$mysqli->query( "SHOW SLAVE STATUS" ) ;
if ( ! $replResult ) {
// Try MySQL 8.0.22+ syntax
$replResult = @$mysqli->query( "SHOW REPLICA STATUS" ) ;
}
if ( ! $replResult ) {
$result['warnings'][] = "REPLICATION CLIENT privilege missing - replica status unavailable. Grant with: GRANT REPLICATION CLIENT ON *.* TO '$dbUser'@'%';" ;
} else {
$replResult->close() ;
}
$mysqli->close() ;
} catch ( \Exception $e ) {
$result['success'] = false ;
$result['errors'][] = "Error: " . $e->getMessage() ;
}
return $result ;
}
// ///////////////////////////////////////////////////////////////////////////
function doLoginOrDie( $page ) {
// Preserve query string parameters through login
$dataParam = Tools::param( 'data' ) ;
$dataHidden = '' ;
if ( ! Tools::isNullOrEmptyString( $dataParam ) ) {
$dataHidden = '<input type="hidden" name="data" value="' . htmlspecialchars( $dataParam, ENT_QUOTES, 'UTF-8' ) . '" />' ;
}
$loginPage = <<<HTML
<h2>Login</h2>
<div>
<form method="post" action="manageData.php">
$dataHidden
<label for="user"><b>Username</b></label>
<input type="text" name="user" required="required" />
<label for="password"><b>Password</b></label>
<input type="password" name="password" required="required" />
<input type="submit" name="submit" value="submit" />
</form>
</div>
HTML;
if ( ! Tools::isNullOrEmptyString( Tools::param( 'logout' ) ) ) {
session_unset() ;
session_destroy() ;
$page->setBody( $loginPage );
$page->displayPage() ;
die() ;
}
if ( ! isset( $_SESSION[ 'AuthUser' ] ) || ( ! isset( $_SESSION[ 'AuthCanAccess' ] ) ) ) {
if ( !Tools::isNullOrEmptyString( Tools::post( 'user', null, 1 ) )
&& !Tools::isNullOrEmptyString( Tools::post( 'password', null, 1 ) )
) {
if ( LDAP::authenticate( Tools::post( 'user', null, 1 ), Tools::post( 'password', null, 1 ) ) ) {
return ; // User was successfully logged in.
}
echo "Login failed: Incorrect user name, password, or access.<br />" ;
}
$page->setBody( $loginPage );
$page->displayPage() ;
die() ;
}
} // END OF doLoginOrDie
// ///////////////////////////////////////////////////////////////////////////
$page = new WebPage( 'AQL: Manage Data' ) ;
$page->setTop( "<h2>AQL: Manage Data</h2>\n"
. "<a href=\"./manageData.php?logout=logout\">Log out of Manage Data</a>\n"
. "<p />\n"
) ;
doLoginOrDie( $page ) ;
switch ( Tools::param( 'data' ) ) {
case 'Hosts':
// Create DB connection early so we can fetch ENUM values for validation
$dbc = new DBConnection();
$dbh = $dbc->getConnection();
$dbh->set_charset('utf8');
// Fetch valid db_type values from ENUM definition in DDL
$validDbTypes = getEnumValues( $dbh, 'host', 'db_type' ) ;
if ( empty( $validDbTypes ) ) {
// Fallback if ENUM fetch fails
$validDbTypes = [ 'MySQL' ] ;
}
// validate input
$body = '' ;
$links = '' ;
$errors = '' ;
$action = Tools::param( 'action' ) ;
$hostId = Tools::param( 'hostId' ) ;
$hostName = Tools::param( 'hostName' ) ;
$portNumber = Tools::param( 'portNumber') ;
$description = Tools::param( 'description' ) ;
$shouldMonitor = Tools::param( 'shouldMonitor' ) ;
$shouldBackup = Tools::param( 'shouldBackup' ) ;
$shouldSchemaspy = Tools::param( 'shouldSchemaspy' ) ;
$revenueImpacting = Tools::param('revenueImpacting' ) ;
$decommissioned = Tools::param( 'decommissioned' ) ;
$alertCritSecs = Tools::param( 'alertCritSecs' ) ;
$alertWarnSecs = Tools::param( 'alertWarnSecs' ) ;
$alertInfoSecs = Tools::param( 'alertInfoSecs' ) ;
$alertLowSecs = Tools::param( 'alertLowSecs' ) ;
$dbType = Tools::param( 'dbType' ) ;
if ( ( ( 'Update' === $action ) || ( 'Delete' === $action ) )
&& ! Tools::isNumeric( $hostId )
) {
$errors .= "Invalid ID\n" ;
}
if ( 'Delete' !== $action ) {
if ( Tools::isNullOrEmptyString( $hostName ) ) {
$errors .= "Host Name cannot be empty.<br />\n" ;
}
checkIsNumeric( $portNumber, "Invalid Port Number.\n", $errors ) ;
checkIs1or0( $shouldMonitor, "Should Monitor", $errors ) ;
checkIs1or0( $shouldBackup, "Should Backup", $errors ) ;
checkIs1or0( $shouldSchemaspy, "Should Schemaspy", $errors ) ;
checkIs1or0( $revenueImpacting, "Revenue Impacting", $errors ) ;
checkIs1or0( $decommissioned, "Decommissioned", $errors ) ;
checkIsNumeric( $alertCritSecs, "Alert Seconds: Critical", $errors ) ;
checkIsNumeric( $alertWarnSecs, "Alert Seconds: Warning", $errors ) ;
checkIsNumeric( $alertInfoSecs, "Alert Seconds: Info", $errors ) ;
checkIsNumeric( $alertLowSecs, "Alert Seconds: Low", $errors ) ;
if ( ! in_array( $dbType, $validDbTypes ) ) {
$errors .= "Invalid Database Type.<br />\n" ;
}
}
if ( ( '' != $errors ) && ( '' != $action ) ) {
$page->setBody( $links . $body . $errors ) ;
$page->displayPage() ;
exit( 0 ) ;
}
// react accordingly
switch ( $action ) {
case '':
// Nothing to see here.
break;
case 'Add':
$body .= 'Add - ' ;
// Verify host permissions before adding
$permCheck = verifyHostPermissions( $hostName, $portNumber ) ;
if ( ! $permCheck['success'] ) {
$config = new Config() ;
$dbUser = $config->getDbUser() ;
$body .= "<span class='msg-error'>Failed - Permission verification failed:</span><br />\n" ;
foreach ( $permCheck['errors'] as $err ) {
$body .= "<span class='msg-error'>• " . htmlspecialchars( $err ) . "</span><br />\n" ;
}
$body .= "<p>Run these commands on <strong>" . htmlspecialchars( $hostName ) . ":" . htmlspecialchars( $portNumber ) . "</strong> to fix:</p>\n" ;
$body .= "<div class='code-box'>\n" ;
$body .= "<pre>" ;
$body .= "-- Create user if it doesn't exist\n" ;
$body .= "CREATE USER IF NOT EXISTS '" . htmlspecialchars( $dbUser ) . "'@'%' IDENTIFIED BY 'YourPasswordHere';\n\n" ;
$body .= "-- Grant required privileges\n" ;
$body .= "GRANT PROCESS ON *.* TO '" . htmlspecialchars( $dbUser ) . "'@'%';\n" ;
$body .= "GRANT REPLICATION CLIENT ON *.* TO '" . htmlspecialchars( $dbUser ) . "'@'%';\n\n" ;
$body .= "-- Apply changes\n" ;
$body .= "FLUSH PRIVILEGES;" ;
$body .= "</pre>\n" ;
$body .= "</div>\n" ;
break ;
}
// Show warnings but proceed with add
if ( ! empty( $permCheck['warnings'] ) ) {
$body .= "<span class='msg-warning'>Warnings:</span><br />\n" ;
foreach ( $permCheck['warnings'] as $warn ) {
$body .= "<span class='msg-warning'>• " . htmlspecialchars( $warn ) . "</span><br />\n" ;
}
}
$sql = 'INSERT INTO host SET hostname = ?, port_number = ?'
. ', description = ?, should_monitor = ?, should_backup = ?'
. ', should_schemaspy = ?, revenue_impacting = ?, decommissioned = ?'
. ', alert_crit_secs = ?, alert_warn_secs = ?'
. ', alert_info_secs = ?, alert_low_secs = ?, db_type = ?'
. ', created = NOW(), updated = NOW(), last_audited = NOW()'
;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'sisiiiiiiiiiis'
, $hostName, $portNumber, $description, $shouldMonitor
, $shouldBackup, $shouldSchemaspy, $revenueImpacting, $decommissioned
, $alertCritSecs, $alertWarnSecs, $alertInfoSecs, $alertLowSecs, $dbType
) ;
$body .= ( $stmt->execute() ) ? "<span class='msg-success'>Success.</span><br />\n" : "Failed.<br />\n" ;
break ;
case 'Update':
$body .= 'Update - ' ;
$sql = 'UPDATE host SET hostname = ?, port_number = ?'
. ', description = ?, should_monitor = ?'
. ', should_backup = ?, should_schemaspy = ?'
. ', revenue_impacting = ?, decommissioned = ?'
. ', alert_crit_secs = ?, alert_warn_secs = ?'
. ', alert_info_secs = ?, alert_low_secs = ?, db_type = ?'
. ', updated = NOW(), last_audited = NOW()'
. ' WHERE host_id = ?'
;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'sisiiiiiiiiisi'
, $hostName, $portNumber, $description, $shouldMonitor
, $shouldBackup, $shouldSchemaspy, $revenueImpacting, $decommissioned
, $alertCritSecs, $alertWarnSecs, $alertInfoSecs, $alertLowSecs, $dbType
, $hostId
) ;
$body .= ( $stmt->execute() ) ? "Success.<br />\n" : "Failed.<br />\n" ;
break ;
case 'Delete':
$body .= 'Delete - ' ;
$sql = 'DELETE FROM host WHERE host_id = ?' ;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'i', $hostId ) ;
$body .= ( $stmt->execute() ) ? "Success.<br />\n" : "Failed.<br />\n" ;
break ;
default:
$page->setBody( $links, 'Huh?' ) ;
$page->displayPage() ;
exit( 0 ) ;
}
$allHostsQuery = <<<SQL
SELECT host_id
, hostname
, port_number
, description
, should_monitor
, should_backup
, should_schemaspy
, revenue_impacting
, decommissioned
, alert_crit_secs
, alert_warn_secs
, alert_info_secs
, alert_low_secs
, db_type
FROM aql_db.host
ORDER BY decommissioned DESC, hostname ASC, port_number ASC
SQL;
// Generate db_type dropdown options dynamically from ENUM values
$dbTypeOptions = '' ;
foreach ( $validDbTypes as $type ) {
$selected = ( $type === 'MySQL' ) ? ' selected="selected"' : '' ;
$dbTypeOptions .= '<option value="' . htmlspecialchars( $type, ENT_QUOTES, 'UTF-8' ) . '"' . $selected . '>'
. htmlspecialchars( $type, ENT_QUOTES, 'UTF-8' ) . '</option>' ;
}
// Form at the top for easier access
$body .= <<<HTML
<form id="AddUpdateDeleteHostForm" action="manageData.php">
<input type="hidden" name="data" value="Hosts">
<table id="AddUpdateDeleteHostTable" border=1 cellspacing=0 cellpadding=2>
<caption>Host Form</caption>
<tr><th colspan="2">ID</th><td><input type="number" id="hostId" name="hostId" readonly="readonly" value="" size=5 /></td></tr>
<tr><th colspan="2">Host Name</th><td><input type="text" id="hostName" name="hostName" size="32" value="" /></td></tr>
<tr><th colspan="2">Port Number</th><td><input type="number" id="portNumber" name="portNumber" size="5" value="3306" /></td></tr>
<tr><th colspan="2">Description</th><td><textarea id="description" name="description" rows="4" cols="60"></textarea></td></tr>
<tr><th colspan="2">DB Type</th><td><select id="dbType" name="dbType">$dbTypeOptions</select></td></tr>
<tr><th colspan="2">Should Monitor</th><td><select id="shouldMonitor" name="shouldMonitor"><option value="1" selected="selected">Yes</option><option value="0">No</option></select></td></tr>
<tr><th colspan="2">Should Backup</th><td><select id="shouldBackup" name="shouldBackup"><option value="1" selected="selected">Yes</option><option value="0">No</option></select></td></tr>
<tr><th colspan="2">Should Schemaspy</th><td><select id="shouldSchemaspy" name="shouldSchemaspy"><option value="1">Yes</option><option value="0" selected="selected">No</option></select></td></tr>
<tr><th colspan="2">Revenue Impacting</th><td><select id="revenueImpacting" name="revenueImpacting"><option value="1" selected="selected">Yes</option><option value="0">No</option></select></td></tr>
<tr><th colspan="2">Decommissioned</th><td><select id="decommissioned" name="decommissioned"><option value="1">Yes</option><option value="0" selected="selected">No</option></select></td></tr>
<tr><th rowspan="4">Alert Seconds</th><th>Critical</th><td><input type="number" id="alertCritSecs" name="alertCritSecs" size="3" value="" /></td></tr>
<tr><th>Warning</th><td><input type="number" id="alertWarnSecs" name="alertWarnSecs" size="3" value="" /></td></tr>
<tr><th>Info</th><td><input type="number" id="alertInfoSecs" name="alertInfoSecs" size="3" value="" /></td></tr>
<tr><th>Low</th><td><input type="number" id="alertLowSecs" name="alertLowSecs" size="3" value="" /></td></tr>
</tr>
</table>
<input type="submit" name="action" value="Add">
<input type="submit" name="action" value="Update">
<input type="submit" name="action" value="Delete">
</form>
<script>
// Default ports for each DB type
var defaultPorts = {
'MySQL': 3306,
'MariaDB': 3306,
'MS-SQL': 1433,
'Redis': 6379,
'RLEC': 6379,
'InnoDBCluster': 3306,
'InnoDBRouter': 6446
};
// Update port when DB type changes (only if port is still a default value)
document.getElementById('dbType').addEventListener('change', function() {
var portField = document.getElementById('portNumber');
var currentPort = parseInt(portField.value, 10);
var isDefaultPort = Object.values(defaultPorts).indexOf(currentPort) !== -1 || portField.value === '';
if (isDefaultPort && defaultPorts[this.value]) {
portField.value = defaultPorts[this.value];
}
});
</script>
<p></p>
<table id="hostEdit" border=1 cellspacing=0 cellpadding=2 class="tablesorter aql-listing">
<thead>
<tr>
<th rowspan="2">Actions</th>
<th rowspan="2">Host ID</th>
<th rowspan="2">Host Name</th>
<th rowspan="2">Port</th>
<th rowspan="2">Description</th>
<th rowspan="2">Should Monitor</th>
<th rowspan="2">Should Backup</th>
<th rowspan="2">Should Schemaspy</th>
<th rowspan="2">Revenue Impacting</th>
<th rowspan="2">Decommissioned</th>
<th colspan="4">Alert Seconds</th>
<th rowspan="2">DB Type</th>
</tr>
<tr>
<th>Critical</th>
<th>Warn</th>
<th>Info</th>
<th>Low</th>
</tr>
</thead>
<tbody>
HTML;
try {
$result = $dbh->query( $allHostsQuery );
if ( ! $result ) {
throw new \ErrorException( "Query failed: $allHostsQuery\n Error: " . $dbh->error );
}
while ( $row = $result->fetch_row() ) {
// Use json_encode for safe JavaScript string escaping, then htmlspecialchars for HTML attribute context
$jsHostname = htmlspecialchars( json_encode( $row[1] ), ENT_QUOTES, 'UTF-8' ) ;
$jsDescription = htmlspecialchars( json_encode( $row[3] ), ENT_QUOTES, 'UTF-8' ) ;
$jsDbType = htmlspecialchars( json_encode( $row[13] ), ENT_QUOTES, 'UTF-8' ) ;
$body .= " <tr>"
. "<td class=\"text-center\">"
. "<button type=\"button\" onclick=\"fillHostForm("
. intval( $row[0] ) . ", "
. $jsHostname . ", "
. intval( $row[2] ) . ", "
. $jsDescription . ", "
. intval( $row[4] ) . ", "
. intval( $row[5] ) . ", "
. intval( $row[6] ) . ", "
. intval( $row[7] ) . ", "
. intval( $row[8] ) . ", "
. intval( $row[9] ) . ", "
. intval( $row[10] ) . ", "
. intval( $row[11] ) . ", "
. intval( $row[12] ) . ", "
. $jsDbType
. "); return false;\">Fill Host Form</button>"
. "</td>"
;
// Columns 4-8 are boolean flags that get color coding
$boolCols = [ 4, 5, 6, 7, 8 ] ;
for ( $i = 0 ; $i < 14 ; $i++ ) {
if ( in_array( $i, $boolCols ) ) {
$class = ( $row[$i] == 1 ) ? 'bool-yes' : 'bool-no' ;
$body .= "<td class=\"$class\">" . htmlspecialchars( $row[$i] ?? '', ENT_QUOTES, 'UTF-8' ) . "</td>" ;
} else {
$body .= "<td>" . htmlspecialchars( $row[$i] ?? '', ENT_QUOTES, 'UTF-8' ) . "</td>" ;
}
}
$body .= "</tr>\n" ;
}
$body .= <<<HTML
</tbody>
</table>
HTML;
$page->setBody( $links . $body ) ;
}
catch (DaoException $e) {
$page->appendBody( "<pre>Error interacting with the database\n\n" . $e->getMessage() . "\n</pre>\n" ) ;
}
$page->displayPage() ;
break ;
case 'Groups':
$body = $links = $errors = '' ;
$action = Tools::param( 'action' ) ;
$groupId = Tools::param( 'groupId' ) ;
$groupTag = Tools::param( 'groupTag' ) ;
$shortDesc = Tools::param( 'shortDescription' ) ;
$fullDesc = Tools::param( 'fullDescription' ) ;
$groupSelection = Tools::params( 'groupSelect' ) ;
if ( ( ( 'Update' === $action ) || ( 'Delete' === $action ) )
&& ! Tools::isNumeric( $groupId )
) {
$errors .= "Invalid ID\n" ;
}
if ( ( 'Add' === $action ) || ( 'Update' === $action ) ) {
if ( Tools::isNullOrEmptyString( $groupTag ) ) {
$errors .= "Tag cannot be empty.<br />\n" ;
}
if ( strlen( $groupTag ) > 16 ) {
$errors .= "Group Tag is too long.<br />\n" ;
}
if ( ! is_array( $groupSelection ) ) {
// Someone is fiddling with the input.
echo "Huh?\n" ; exit( 0 ) ;
}
$countIsValid = 0 ;
// Check each of the $groupSelection array members
foreach ( $groupSelection as $value ) {
if ( ! Tools::isNumeric( $value ) ) {
// Someone is fiddling with the input.
echo "Huh?\n" ; exit( 1 ) ;
}
$countIsValid = 1 ;
}
if ( 0 === $countIsValid ) {
$errors .= "Must specify at least one host in group.<br />\n" ;
}
}
if ( $errors !== '' ) {
$page->setBody( $links . $errors ) ;
$page->displayPage() ;
exit( 0 );
}
$dbc = new DBConnection() ;
$dbh = $dbc->getConnection() ;
$dbh->set_charset('utf8') ;
// Handle group change
switch ( $action ) {
case '':
// Nothing to see here.
break ;
case 'Add':
$body .= 'Add - ' ;
$sql = 'INSERT INTO host_group SET tag = ?'
. ', short_description = ?'
. ', full_description = ?'
. ', created = CURRENT_TIMESTAMP()'
. ', updated = CURRENT_TIMESTAMP()'
;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'sss', $groupTag, $shortDesc, $fullDesc ) ;
$body .= ( $stmt->execute() ) ? "Success.<br />\n" : "Failed.<br />\n" ;
// get new $groupId
$groupId = $dbh->insert_id ;
break ;
case 'Update':
$body .= 'Update - ' ;
$sql = 'UPDATE host_group SET tag = ?'
. ', short_description = ?'
. ', full_description = ?'
. ', updated = CURRENT_TIMESTAMP()'
. ' WHERE host_group_id = ?'
;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'sssi', $groupTag, $shortDesc, $fullDesc, $groupId ) ;
$body .= ( $stmt->execute() ) ? "Success.<br />\n" : "Failed.<br />\n" ;
break ;
case 'Delete':
$body .= 'Delete - ' ;
$sql = 'DELETE FROM host_group_map WHERE host_group_id = ?' ;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'i', $groupId ) ;
if ( ! $stmt->execute() ) {
echo "Conflicting update?<br />\n" ;
exit( 1 ) ;
}
$sql = 'DELETE FROM host_group WHERE host_group_id = ?' ;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'i', $groupId ) ;
$body .= ( $stmt->execute() ) ? "Success.<br />\n" : "Failed.<br />\n" ;
break ;
default:
$page->setBody( $links . 'Huh?' ) ;
$page->displayPage() ;
exit( 0 );
}
if ( 'Update' === $action ) {
// Delete group members not in the selected list
if ( !empty( $groupSelection ) ) {
$placeholders = implode( ',', array_fill( 0, count( $groupSelection ), '?' ) ) ;
$sql = "DELETE FROM host_group_map WHERE host_group_id = ? AND host_id NOT IN ($placeholders)" ;
$stmt = $dbh->prepare( $sql ) ;
$types = 'i' . str_repeat( 'i', count( $groupSelection ) ) ;
$params = array_merge( [ $groupId ], $groupSelection ) ;
$stmt->bind_param( $types, ...$params ) ;
if ( ! $stmt->execute() ) {
echo "Conflicting update?<br />\n" ;
exit( 1 ) ;
}
} else {
// No hosts selected - delete all mappings for this group
$sql = "DELETE FROM host_group_map WHERE host_group_id = ?" ;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'i', $groupId ) ;
if ( ! $stmt->execute() ) {
echo "Conflicting update?<br />\n" ;
exit( 1 ) ;
}
}
}
if ( ( 'Add' === $action ) || ( 'Update' === $action ) ) {
// Add group members
$sql = "INSERT IGNORE INTO host_group_map"
. " SET host_group_id = ?, host_id = ?, created = NOW(), updated = NOW(), last_audited = NOW()"
;
$stmt = $dbh->prepare( $sql ) ;
foreach ( $groupSelection as $hostId ) {
$stmt->bind_param( "ii", $groupId, $hostId ) ;
$stmt->execute() ;
}
}
$groupQuery = <<<SQL
SELECT hg.host_group_id
, hg.tag
, hg.short_description
, hg.full_description
, COUNT( hgm.host_id ) as host_cnt
, GROUP_CONCAT( DISTINCT hgm.host_id ) as host_list
FROM host_group AS hg
LEFT
JOIN host_group_map AS hgm USING ( host_group_id )
GROUP BY hg.host_group_id
ORDER BY hg.tag
SQL;
$hostsQuery = <<<SQL
SELECT host_id, CONCAT( hostname, ':', port_number )
FROM aql_db.host
WHERE decommissioned = 0
ORDER BY hostname, port_number
SQL;
try {
// Build host select dropdown first (needed for form)
$hostResult = $dbh->query( $hostsQuery ) ;
if ( ! $hostResult ) {
throw new \ErrorException( "Query failed: $hostsQuery\n Error: " . $dbh->error ) ;
}
$groupSelect = "<select name=\"groupSelect[]\" id=\"groupSelect\" size=\"25\" multiple=\"multiple\">\n" ;
while ( $row = $hostResult->fetch_row() ) {
$groupSelect .= " <option value=\"" . intval( $row[0] ) . "\">"
. htmlspecialchars( $row[1], ENT_QUOTES, 'UTF-8' ) . "</option>\n" ;
}
$groupSelect .= "</select>\n" ;
// Form at the top for easier access
$body .= <<<HTML
<form method="get" action="manageData.php">
<input type="hidden" name="data" value="Groups">
<table id="Form" border=1 cellspacing=0 cellpadding=2>
<caption>Group Form</caption>
<tr><th>Group ID</th><td><input type="number" id="groupId" name="groupId" readonly="readonly" size=5 /></td></tr>
<tr><th>Group Tag (16)</th><td><input type="text" id="groupTag" name="groupTag" size="16" maxlength="16" /></td></tr>
<tr><th>Description</th><td><input type="text" id="shortDescription" name="shortDescription" size="80" maxlength="255" /></td></tr>
<tr><th>Full Description</th><td><textarea id="fullDescription" name="fullDescription" rows="4" cols="80" maxlength="65535"></textarea></td></tr>
<tr><th>Members</th><td>$groupSelect</td></tr>
</table>
<input type="submit" name="action" value="Add">
<input type="submit" name="action" value="Update">
<input type="submit" name="action" value="Delete">
<br clear="all" />
</form>
<p></p>
<table id="groupEdit" border=1 cellspacing=0 cellpadding=2 class="tablesorter aql-listing">
<thead>
<tr>
<th>Actions</th>
<th>Group ID</th>
<th>Group Tag</th>
<th>Description</th>
<th>Full Description</th>
<th>Member Count</th>
</tr>
</thead>
<tbody>
HTML;
$groupResult = $dbh->query( $groupQuery ) ;
if ( ! $groupResult ) {
throw new \ErrorException( "Query failed: $groupQuery\n Error: " . $dbh->error ) ;
}
while ( $row = $groupResult->fetch_row() ) {
// Use json_encode for safe JavaScript string escaping, then htmlspecialchars for HTML attribute context
$jsTag = htmlspecialchars( json_encode( $row[1] ), ENT_QUOTES, 'UTF-8' ) ;
$jsShortDesc = htmlspecialchars( json_encode( $row[2] ), ENT_QUOTES, 'UTF-8' ) ;
$jsFullDesc = htmlspecialchars( json_encode( $row[3] ), ENT_QUOTES, 'UTF-8' ) ;
// host_list is comma-separated integers from GROUP_CONCAT, sanitize to be safe
$hostList = $row[5] ? preg_replace( '/[^0-9,]/', '', $row[5] ) : '' ;
$body .= " <tr>"
. "<td><button type=\"button\""
. " onclick=\"fillGroupForm(" . intval( $row[0] ) . ", $jsTag, $jsShortDesc, $jsFullDesc, [$hostList]); return false;\""
. ">Fill In Form</button></td>"
;
for ( $i = 0 ; $i < 5 ; $i++ ) {
$body .= "<td>" . htmlspecialchars( $row[$i] ?? '', ENT_QUOTES, 'UTF-8' ) . "</td>" ;
}
$body .= "</tr>\n" ;
}
$body .= <<<HTML
</tbody>
</table>
HTML;
$page->setBody( $links . $body ) ;
}
catch (DaoException $e) {
$page->appendBody( "<pre>Error interacting with the database\n\n" . $e->getMessage() . "\n</pre>\n" ) ;
}
$page->displayPage() ;
break ;
case 'MaintenanceWindows':
$dbc = new DBConnection();
$dbh = $dbc->getConnection();
$dbh->set_charset('utf8');
$body = $links = $errors = '' ;
$action = Tools::param( 'action' ) ;
$windowId = Tools::param( 'windowId' ) ;
$windowType = Tools::param( 'windowType' ) ;
$scheduleType = Tools::param( 'scheduleType' ) ;
$targetType = Tools::param( 'targetType' ) ; // 'host' or 'group'
$targetId = Tools::param( 'targetId' ) ;
$daysOfWeek = Tools::params( 'daysOfWeek' ) ; // array
$dayOfMonth = Tools::param( 'dayOfMonth' ) ;
$monthOfYear = Tools::param( 'monthOfYear' ) ;
$periodDays = Tools::param( 'periodDays' ) ;
$periodStartDate = Tools::param( 'periodStartDate' ) ;
$startTime = Tools::param( 'startTime' ) ;
$endTime = Tools::param( 'endTime' ) ;
$timezone = Tools::param( 'timezone' ) ;
$silenceUntil = Tools::param( 'silenceUntil' ) ;
$description = Tools::param( 'description' ) ;
// Validation
if ( ( ( 'Update' === $action ) || ( 'Delete' === $action ) )
&& ! Tools::isNumeric( $windowId )
) {
$errors .= "Invalid Window ID<br />\n" ;
}
if ( 'Delete' !== $action && '' !== $action ) {
if ( ! in_array( $windowType, [ 'scheduled', 'adhoc' ] ) ) {
$errors .= "Window Type must be 'scheduled' or 'adhoc'<br />\n" ;
}
if ( ! in_array( $targetType, [ 'host', 'group' ] ) ) {
$errors .= "Target Type must be 'host' or 'group'<br />\n" ;
}
if ( ! Tools::isNumeric( $targetId ) || $targetId <= 0 ) {
$errors .= "Please select a valid Host or Group<br />\n" ;
}
if ( 'scheduled' === $windowType ) {
// Validate schedule type
if ( ! in_array( $scheduleType, [ 'weekly', 'monthly', 'quarterly', 'annually', 'periodic' ] ) ) {
$errors .= "Schedule Type must be one of: weekly, monthly, quarterly, annually, periodic<br />\n" ;
}
// Schedule-type-specific validation
if ( 'weekly' === $scheduleType ) {
if ( empty( $daysOfWeek ) ) {
$errors .= "Please select at least one day of the week<br />\n" ;
}
}
if ( in_array( $scheduleType, [ 'monthly', 'quarterly', 'annually' ] ) ) {
if ( ! Tools::isNumeric( $dayOfMonth ) || $dayOfMonth < 1 || $dayOfMonth > 32 ) {
$errors .= "Day of Month must be between 1 and 32<br />\n" ;
}
}
if ( in_array( $scheduleType, [ 'quarterly', 'annually' ] ) ) {
$maxMonth = ( 'quarterly' === $scheduleType ) ? 3 : 12 ;
if ( ! Tools::isNumeric( $monthOfYear ) || $monthOfYear < 1 || $monthOfYear > $maxMonth ) {
$errors .= "Month must be between 1 and $maxMonth<br />\n" ;
}
}
if ( 'periodic' === $scheduleType ) {
if ( ! Tools::isNumeric( $periodDays ) || $periodDays < 1 ) {
$errors .= "Period Days must be at least 1<br />\n" ;
}
if ( empty( $periodStartDate ) ) {
$errors .= "Period Start Date is required for periodic schedules<br />\n" ;
}
}
// All scheduled types need start/end time
if ( empty( $startTime ) || empty( $endTime ) ) {
$errors .= "Start Time and End Time are required for scheduled windows<br />\n" ;
}
}
if ( 'adhoc' === $windowType ) {
if ( empty( $silenceUntil ) ) {
$errors .= "Silence Until is required for ad-hoc windows<br />\n" ;
}
}
}
if ( ( '' != $errors ) && ( '' != $action ) ) {
$page->setBody( $links . $body . $errors ) ;
$page->displayPage() ;
exit( 0 ) ;
}
// Process action
switch ( $action ) {
case '':
break;
case 'Add':
$body .= 'Add - ' ;
// Convert days array to SET string
$daysSet = is_array( $daysOfWeek ) ? implode( ',', $daysOfWeek ) : '' ;
// Prepare values (use null for empty)
$scheduleTypeVal = ( 'scheduled' === $windowType ) ? $scheduleType : null ;
$daysSetVal = empty( $daysSet ) ? null : $daysSet ;
$dayOfMonthVal = empty( $dayOfMonth ) ? null : intval( $dayOfMonth ) ;
$monthOfYearVal = empty( $monthOfYear ) ? null : intval( $monthOfYear ) ;
$periodDaysVal = empty( $periodDays ) ? null : intval( $periodDays ) ;
$periodStartDateVal = empty( $periodStartDate ) ? null : $periodStartDate ;
$startTimeVal = empty( $startTime ) ? null : $startTime ;
$endTimeVal = empty( $endTime ) ? null : $endTime ;
$silenceUntilVal = empty( $silenceUntil ) ? null : $silenceUntil ;
$createdBy = $_SESSION['AuthUser'] ?? '' ;
$sql = 'INSERT INTO maintenance_window SET window_type = ?, schedule_type = ?, days_of_week = ?, day_of_month = ?, month_of_year = ?, period_days = ?, period_start_date = ?, start_time = ?, end_time = ?, timezone = ?, silence_until = ?, description = ?, created_by = ?' ;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'sssiiiissssss', $windowType, $scheduleTypeVal, $daysSetVal, $dayOfMonthVal, $monthOfYearVal, $periodDaysVal, $periodStartDateVal, $startTimeVal, $endTimeVal, $timezone, $silenceUntilVal, $description, $createdBy ) ;
if ( $stmt->execute() ) {
$newWindowId = $dbh->insert_id ;
// Add to mapping table
if ( 'host' === $targetType ) {
$mapSql = 'INSERT INTO maintenance_window_host_map (window_id, host_id) VALUES (?, ?)' ;
} else {
$mapSql = 'INSERT INTO maintenance_window_host_group_map (window_id, host_group_id) VALUES (?, ?)' ;
}
$mapStmt = $dbh->prepare( $mapSql ) ;
$mapStmt->bind_param( 'ii', $newWindowId, $targetId ) ;
$mapStmt->execute() ;
$body .= "Added window ID $newWindowId<br />\n" ;
} else {
$body .= "Error: " . $dbh->error . "<br />\n" ;
}
break;
case 'Update':
$body .= 'Update - ' ;
// Convert days array to SET string
$daysSet = is_array( $daysOfWeek ) ? implode( ',', $daysOfWeek ) : '' ;
// Prepare values (use null for empty)
$scheduleTypeVal = ( 'scheduled' === $windowType ) ? $scheduleType : null ;
$daysSetVal = empty( $daysSet ) ? null : $daysSet ;
$dayOfMonthVal = empty( $dayOfMonth ) ? null : intval( $dayOfMonth ) ;
$monthOfYearVal = empty( $monthOfYear ) ? null : intval( $monthOfYear ) ;
$periodDaysVal = empty( $periodDays ) ? null : intval( $periodDays ) ;
$periodStartDateVal = empty( $periodStartDate ) ? null : $periodStartDate ;
$startTimeVal = empty( $startTime ) ? null : $startTime ;
$endTimeVal = empty( $endTime ) ? null : $endTime ;
$silenceUntilVal = empty( $silenceUntil ) ? null : $silenceUntil ;
$sql = 'UPDATE maintenance_window SET window_type = ?, schedule_type = ?, days_of_week = ?, day_of_month = ?, month_of_year = ?, period_days = ?, period_start_date = ?, start_time = ?, end_time = ?, timezone = ?, silence_until = ?, description = ? WHERE window_id = ?' ;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'sssiiissssssi', $windowType, $scheduleTypeVal, $daysSetVal, $dayOfMonthVal, $monthOfYearVal, $periodDaysVal, $periodStartDateVal, $startTimeVal, $endTimeVal, $timezone, $silenceUntilVal, $description, $windowId ) ;
if ( $stmt->execute() ) {
// Update mapping - remove old, add new
$dbh->query( "DELETE FROM maintenance_window_host_map WHERE window_id = $windowId" ) ;
$dbh->query( "DELETE FROM maintenance_window_host_group_map WHERE window_id = $windowId" ) ;
if ( 'host' === $targetType ) {
$mapSql = 'INSERT INTO maintenance_window_host_map (window_id, host_id) VALUES (?, ?)' ;
} else {
$mapSql = 'INSERT INTO maintenance_window_host_group_map (window_id, host_group_id) VALUES (?, ?)' ;
}
$mapStmt = $dbh->prepare( $mapSql ) ;
$mapStmt->bind_param( 'ii', $windowId, $targetId ) ;
$mapStmt->execute() ;
$body .= "Updated window ID $windowId<br />\n" ;
} else {
$body .= "Error: " . $dbh->error . "<br />\n" ;
}
break;
case 'Delete':
$body .= 'Delete - ' ;
// Foreign keys with CASCADE will handle mapping table cleanup
$sql = 'DELETE FROM maintenance_window WHERE window_id = ?' ;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'i', $windowId ) ;
if ( $stmt->execute() ) {
$body .= "Deleted window ID $windowId<br />\n" ;
} else {
$body .= "Error: " . $dbh->error . "<br />\n" ;
}
break;
}
// Fetch hosts and groups for dropdowns
$hostsResult = $dbh->query( 'SELECT host_id, CONCAT(hostname, ":", port_number) AS display FROM host ORDER BY hostname, port_number' ) ;
$hostOptions = '<option value="">-- Select Host --</option>' ;
while ( $row = $hostsResult->fetch_assoc() ) {
$hostOptions .= '<option value="' . $row['host_id'] . '">' . htmlspecialchars( $row['display'], ENT_QUOTES, 'UTF-8' ) . '</option>' ;
}
$groupsResult = $dbh->query( 'SELECT host_group_id, tag FROM host_group ORDER BY tag' ) ;
$groupOptions = '<option value="">-- Select Group --</option>' ;
while ( $row = $groupsResult->fetch_assoc() ) {
$groupOptions .= '<option value="' . $row['host_group_id'] . '">' . htmlspecialchars( $row['tag'], ENT_QUOTES, 'UTF-8' ) . '</option>' ;
}
// Form
$body .= <<<HTML
<form id="MaintenanceWindowForm" action="manageData.php">
<input type="hidden" name="data" value="MaintenanceWindows">
<table id="MaintenanceWindowTable" border=1 cellspacing=0 cellpadding=2>
<caption>Maintenance Window Form</caption>
<tr><th>Window ID</th><td><input type="number" id="windowId" name="windowId" readonly="readonly" value="" size=5 /></td></tr>
<tr><th>Window Type <a onclick="alert('Scheduled: Recurring window that repeats on a schedule.\\n\\nAd-hoc: One-time silencing until a specific date/time (e.g., while working an issue).'); return false;" class="help-cursor">?</a></th><td>
<select id="windowType" name="windowType" onchange="toggleWindowTypeFields()">
<option value="scheduled">Scheduled (Recurring)</option>
<option value="adhoc">Ad-hoc (One-time)</option>
</select>
</td></tr>
<tr id="scheduleTypeRow"><th>Schedule Type <a onclick="alert('Weekly: Repeats on selected days each week.\\n\\nMonthly: Repeats on a specific day each month (e.g., 1st, 15th, or last day).\\n\\nQuarterly: Repeats on a specific day of a specific month each quarter.\\n\\nAnnually: Repeats on a specific date each year.\\n\\nPeriodic: Repeats every N days from a start date.'); return false;" class="help-cursor">?</a></th><td>
<select id="scheduleType" name="scheduleType" onchange="toggleScheduleTypeFields()">
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
<option value="quarterly">Quarterly</option>
<option value="annually">Annually</option>
<option value="periodic">Periodic (Every N Days)</option>
</select>
</td></tr>
<tr><th>Target Type</th><td>
<select id="targetType" name="targetType" onchange="toggleTargetFields()">
<option value="host">Host</option>
<option value="group">Group</option>
</select>
</td></tr>
<tr id="hostRow"><th>Host</th><td>
<select id="targetHost" name="targetId">$hostOptions</select>
</td></tr>
<tr id="groupRow" style="display:none;"><th>Group</th><td>
<select id="targetGroup">$groupOptions</select>
</td></tr>
<tr id="daysRow"><th>Days of Week</th><td>
<label><input type="checkbox" name="daysOfWeek[]" value="Sun"> Sun</label>
<label><input type="checkbox" name="daysOfWeek[]" value="Mon"> Mon</label>
<label><input type="checkbox" name="daysOfWeek[]" value="Tue"> Tue</label>