File: status_query.cgi.in

package info (click to toggle)
nagios-plugin-check-multi 0.26-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,172 kB
  • sloc: perl: 2,296; makefile: 415; sh: 239
file content (743 lines) | stat: -rw-r--r-- 26,321 bytes parent folder | download | duplicates (7)
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
#!@client_perl@
#
# nagios_status (query nagios services from status.dat)
#
# Copyright (c) 2007 Matthias Flacke (matthias.flacke at gmx.de)
#
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# $Id$
#
# Copy this file into <nagiosdir>/sbin and start the CGI via
# http://<hostname>/nagios/cgi-bin/status_query.cgi (YMMV)
#
use strict;
use CGI qw(:standard -debug escape);
use CGI::Carp qw(fatalsToBrowser);
BEGIN { eval("use Time::HiRes qw(time)") }
#use Data::Dumper;

#-----------------------------------------------------------------------------
#--- adopt this value to your local installation -----------------------------
#-----------------------------------------------------------------------------

my $STATUSDAT="@localstatedir@/status.dat"; # location of status.dat

#-----------------------------------------------------------------------------
#--- nothing to change from here ;-) -----------------------------------------
#-----------------------------------------------------------------------------

#--- detect from URL how we've been called
my $MYSELF=url(-relative=>1);
my ($CGI_BIN)=(url()=~/(.*)\/$MYSELF/);
my ($NAGIOS_URL)=(url()=~/(.*)\/cgi-bin\/$MYSELF/);

#--- vars
my $query="";
my @numops=(">",">=","==","!=","<","<=");
my @strops=("=~","!~","eq","ne");
my @allops=(@strops,@numops);
my $ops={
	"NUMERICAL" => \@numops,
	"STRING"    => \@strops,
	"TIMESTAMP" => \@numops,
	"UNKNOWN"   => \@allops,
};
my @st=("OK","WARNING","CRITICAL","UNKNOWN");
my @fg=("OK","WARNING","CRITICAL","UNKNOWN");
my @bg=("Even","BGWARNING","BGCRITICAL","BGUNKNOWN");
my $fields;
my @ftype=();
my @opref=();

#--- status.dat fields (retrieved from <nagiossrc>/include/statusdata.h)
my $statusfields={
   "host"=>{
        acknowledgement_type                     => "NUMERICAL",
        active_checks_enabled                    => "NUMERICAL",
        check_command                            => "STRING",
        check_execution_time                     => "NUMERICAL",
        check_interval                           => "NUMERICAL",
        check_latency                            => "NUMERICAL",
        check_options                            => "NUMERICAL",
        check_period                             => "STRING",
        check_type                               => "NUMERICAL",
        current_attempt                          => "NUMERICAL",
        current_event_id                         => "NUMERICAL",
        current_event_id                         => "NUMERICAL",
        current_notification_id                  => "NUMERICAL",
        current_notification_number              => "NUMERICAL",
        current_problem_id                       => "NUMERICAL",
        current_state                            => "NUMERICAL",
        event_handler                            => "STRING",
        event_handler_enabled                    => "NUMERICAL",
        failure_prediction_enabled               => "NUMERICAL",
        flap_detection_enabled                   => "NUMERICAL",
        has_been_checked                         => "NUMERICAL",
        host_name                                => "STRING",
        is_flapping                              => "NUMERICAL",
        last_check                               => "TIMESTAMP",
        last_event_id                            => "NUMERICAL",
        last_event_id                            => "NUMERICAL",
        last_hard_state                          => "NUMERICAL",
        last_hard_state_change                   => "TIMESTAMP",
        last_notification                        => "NUMERICAL",
        last_problem_id                          => "NUMERICAL",
        last_state_change                        => "TIMESTAMP",
        last_time_down                           => "TIMESTAMP",
        last_time_unreachable                    => "TIMESTAMP",
        last_time_up                             => "TIMESTAMP",
        last_update                              => "TIMESTAMP",
        long_plugin_output                       => "STRING",
        max_attempts                             => "NUMERICAL",
        modified_attributes                      => "NUMERICAL",
        next_check                               => "TIMESTAMP",
        next_notification                        => "TIMESTAMP",
        no_more_notifications                    => "NUMERICAL",
        notification_period                      => "STRING",
        notifications_enabled                    => "NUMERICAL",
        obsess_over_host                         => "NUMERICAL",
        passive_checks_enabled                   => "NUMERICAL",
        percent_state_change                     => "NUMERICAL",
        performance_data                         => "STRING",
        plugin_output                            => "STRING",
        problem_has_been_acknowledged            => "NUMERICAL",
        process_performance_data                 => "NUMERICAL",
        retry_interval                           => "NUMERICAL",
        scheduled_downtime_depth                 => "NUMERICAL",
        should_be_scheduled                      => "NUMERICAL",
        state_type                               => "NUMERICAL",
  },
  "service"=>{
        acknowledgement_type                     => "NUMERICAL",
        active_checks_enabled                    => "NUMERICAL",
        check_command                            => "STRING",
        check_execution_time                     => "NUMERICAL",
        check_interval                           => "NUMERICAL",
        check_latency                            => "NUMERICAL",
        check_options                            => "NUMERICAL",
        check_period                             => "STRING",
        check_type                               => "NUMERICAL",
        current_attempt                          => "NUMERICAL",
        current_event_id                         => "NUMERICAL",
        current_notification_id                  => "NUMERICAL",
        current_notification_number              => "NUMERICAL",
        current_problem_id                       => "NUMERICAL",
        current_state                            => "NUMERICAL",
        event_handler                            => "UNKNOWN",
        event_handler_enabled                    => "NUMERICAL",
        failure_prediction_enabled               => "NUMERICAL",
        flap_detection_enabled                   => "NUMERICAL",
        has_been_checked                         => "NUMERICAL",
        host_name                                => "STRING",
        is_flapping                              => "NUMERICAL",
        last_check                               => "TIMESTAMP",
        last_event_id                            => "NUMERICAL",
        last_hard_state                          => "NUMERICAL",
        last_hard_state_change                   => "TIMESTAMP",
        last_notification                        => "TIMESTAMP",
        last_problem_id                          => "NUMERICAL",
        last_state_change                        => "TIMESTAMP",
        last_time_critical                       => "TIMESTAMP",
        last_time_ok                             => "TIMESTAMP",
        last_time_unknown                        => "NUMERICAL",
        last_time_warning                        => "NUMERICAL",
        last_update                              => "TIMESTAMP",
        long_plugin_output                       => "STRING",
        max_attempts                             => "NUMERICAL",
        modified_attributes                      => "NUMERICAL",
        next_check                               => "TIMESTAMP",
        next_notification                        => "TIMESTAMP",
        no_more_notifications                    => "NUMERICAL",
        notification_period                      => "STRING",
        notifications_enabled                    => "NUMERICAL",
        obsess_over_service                      => "NUMERICAL",
        passive_checks_enabled                   => "NUMERICAL",
        percent_state_change                     => "NUMERICAL",
        performance_data                         => "STRING",
        plugin_output                            => "STRING",
        problem_has_been_acknowledged            => "NUMERICAL",
        process_performance_data                 => "NUMERICAL",
        retry_interval                           => "NUMERICAL",
        scheduled_downtime_depth                 => "NUMERICAL",
        service_description                      => "STRING",
        should_be_scheduled                      => "NUMERICAL",
        state_type                               => "NUMERICAL",
  },
};
my $JSCRIPT=<<EOJSCRIPT;
function check_value(string,type) {
	if (type=="NUMERICAL") {
	        for(var i=0;i<val.length;i++){
			if(!isNumerical(val.charAt(i))){
				alert(string + ' is not numerical!');
				return false;
			}
		}
	} else if (type=="TIMEDATE") {
		if (string.length > 10) {
			alert(string + ' exceeds maximum length of 10 digits!');
			return false;
		}
	        for(var i=0;i<val.length;i++){
			if(!isNumerical(val.charAt(i))){
				alert(string + ' is not numerical!');
				return false;
			}
		}
	}
	alert(string + ' is OK - ' + type + ' - ' + string.length);
	return true;
}
function isNumeric(val){
        return(parseFloat(val,10)==(val*1));
}
EOJSCRIPT
my $PSCRIPT=<<EOPSCRIPT;
	print ">>>$$<<<";
EOPSCRIPT

#-----------------------------------------------------------------------------
#--- Main --------------------------------------------------------------------
#-----------------------------------------------------------------------------
$SIG{ALRM} = sub { kill 9,$$; };

alarm(10);


#--- print HTML header with nagios stylesheets
print header(
	-target=>'main',	# frame target for Nagios
	-expires=>'now',	# do not cache results
);
print "<LINK REL='stylesheet' TYPE='text/css' HREF='$NAGIOS_URL/stylesheets/common.css'>";
print "<LINK REL='stylesheet' TYPE='text/css' HREF='$NAGIOS_URL/stylesheets/status.css'>";
print start_html(
	-title=>'Nagios Query',
	-author=>'Matthias.Flacke@gmx.de',
	-target=>'main',
	-meta=>{
		'copyright'=>'2008-2009 Matthias Flacke',
	},
	-script=>$JSCRIPT,
	-base=>'target="main"',
	-xbase=>url,
);
#--- if statusdat parameter is set, take it as file path
if (defined(param('statusdat')) && param('statusdat')) {
	if (-f param('statusdat')) {
		$STATUSDAT=param('statusdat');
	} else {
		print i,"status.dat file " . param('statusdat') . " not found!";
	}
}

#--- create form
print hr;
print start_multipart_form(
	-target=>'main',
);
print hidden(-name=>'nqueries',-default=>1);
param('nqueries',1) if (param('nqueries')<1);
print hidden(-name=>'sort_order',-default=>1);
param('sort_order',1) if (param('sort_order') != 1 && param('sort_order') != 0);
print "<table>";

#--- loop over number of queries
for (my $i=0;$i<param('nqueries');$i++) {

	#--- check if removal button ('-') has been pressed
	print hidden(-name=>'remove'.$i,-default=>0);

	#--- yes -> don't show row, reset remove flag and correct number of rows
	if (param('nqueries')>1 && param('remove'.$i) eq "1") {
		param('remove'.$i,"0");
		param('nqueries',param('nqueries')-1);
		next;
	} else {
		param('remove'.$i,"0");
	}
	#print "<tr><td>nqueries:",param('nqueries'),"</td><td>i:",$i,"</td></tr>";
	print "<tr><td></td><td></td></tr>";
	print "<tr>";


	#print "<br>$i: qtype:".param('qtype')." qfield$i:".param('qfield'.$i)." qop$i:".param('qop'.$i)." qexpr$i:".param('qexpr'.$i)." ";

	#--- 1. only in first line: Labels and selection of query source [host|service]
	if ($i==0) {
		print "<td>Query<td>";
		print "<td>";
		print popup_menu(
			-name=>'qtype',
			-values=>['service','host'],
			-default=>'service',
			-onChange=>'this.form.qexpr'.$i.'.valuea\'\';this.form.qfield'.$i.'.value=\'plugin_output\';this.form.qop'.$i.'.value=\'=~\';this.form.submit();'
		);
		param('qtype',"service") if (param('qtype') eq "");
		print "</td>";
		print "<td>Expression</td>";
	#---    following lines: placeholders
	} else {
		print "<td></td><td></td><td></td><td>";
	}

	#--- 2. fields popup (filled with field names retrieved from status.dat)
	@{$fields->[$i]}=sort keys %{$$statusfields{param('qtype')}};
	print "<td>";
	print popup_menu(
		-name=>"qfield$i",
		-values=>$fields->[$i],
		-default=>'plugin_output',
		-onChange=>'this.form.qexpr'.$i.'.value=\'\';this.form.qop'.$i.'.value=\'\';this.form.submit();'
	);
	param('qfield'.$i,"plugin_output") if (param('qfield'.$i) eq "");
	print "</td>";

	#--- 3. operators - depending on field type
	$ftype[$i]=get_field_type(param('qtype'),param('qfield'.$i));
	#print "field $i type:$ftype[$i] ";
	$opref[$i]=$$ops{$ftype[$i]};
	print "<td>";
	print popup_menu(
		-name=>"qop$i",
		-values=>$opref[$i],
		#-default=>@{$opref[$i]}->[0],
		-onChange=>'this.form.qexpr'.$i.'.value=\'\';this.form.submit();'
	);
	param('qop'.$i,$ops->{"STRING"}) if (param('qop'.$i) eq "");
	print "</td>";

	#--- 4. input field
	print "<td>";
	print textfield(
		-name=>"qexpr$i",
		-default=>'',
		-size=>20,
		#-maxlength=>($ftype[$i] eq "TIMESTAMP") ? 10 : ($ftype[$i] eq "NUMERICAL") ? 20 : 40,
	);
	print "</td>";

	
	#--- 5.-7. only in the last line
 	if ($i == param('nqueries')-1) {

		#--- 5. plus field (add another line of input)
		print "<td>",button(-name=>"plus$i",-value=>'+',-onClick=>'this.form.nqueries.value++;this.form.submit();'),"</td>";

		#--- 6. minus field (remove a (TODO:this) line of input)
 		if ($i>0) {
			print "<td>",button(-name=>"minus$i",-value=>'-',-onClick=>'this.form.nqueries.value--;this.form.submit();'),"</td>";
		}

		#--- 7. at last: submit button in last line
		print "<td>";
		print submit(
			-name=>'Submit query',
			-onSubmit=>'if (!check_value(this.form.qexpr'.$i.'.value,"'.$ftype[$i].'")) { this.form.qexpr'.$i.'.value=\'\'; }',
		);
		print "</td>";
		#--- multiple rows? add radiobutton in the last line to query AND or OR
		if ($i>0) {
			#print "</tr><td>nqueries:".param('nqueries')."</td><td></td><td></td><td></td>";
			print "</tr><td></td><td></td><td></td><td></td>";
			print "<td colspan=5>";
			print radio_group(
				-name=>'qany_or_all',
				-values=>['match ALL expressions','match ANY expression'],
				-default=>'match ALL expressions',
				-rows=>1,
				-columns=>2,
			);
			param('qany_or_all',"match ALL expressions") if (param('qany_or_all') eq "");
			print "</td>";
		}
	}
	print "</tr>";
}
print "</table>";
print end_form;
print hr;

#--- if debug parameter set, print some values
if (defined(param('debug')) && param('debug')) {
	my %gfields=(
		"CGI_BIN"	=> $CGI_BIN,
		"NAGIOS_URL"	=> $NAGIOS_URL,
		"STATUSDAT"	=> $STATUSDAT,
		"param(statusdat)"=> param('statusdat'),
	);
	my %fields=(
		"query type"	=> 'qtype',
		"query field"	=> 'qfield',
		"query operator"=> 'qop',
		"query expr"	=> 'qexpr',
		"field type"	=> \@ftype,
		
	);
	print sup;
	print "<table>";
	foreach my $key(sort keys %gfields) {
		print "<tr><td>$key</td><td>$fields{$key}</td></tr>";
	}
	for (my $i=0;$i<param('nqueries');$i++) {
		foreach my $key(sort keys %gfields) {
			if ($fields{$key}=~/^q/) {
				print "<tr><td>$i $key</td><td>".param("$key$i")."</td></tr>";
			} else {
				print "<tr><td>$i $key</td><td>$fields{$key}->[$i]</td></tr>";
			}
		}
	}
	print "</table>";
}

#--- queries
my $starttime=time;
my @q=();
for (my $i=0;$i<param('nqueries');$i++) {

	#--- launch query for field
	@{$q[$i]}=get_status(param('qtype'),param('qfield'.$i),param('qop'.$i),param('qexpr'.$i));


	# printf "$i qtype:%s qfield%d:%s qop%d:%s qexpr%d:%s<br><br>",
	#	param('qtype'),$i,param('qfield'.$i),$i,param('qop'.$i),$i,param('qexpr'.$i);
		#my $dump=Dumper($q[$i]);
		#$dump=~s/\n/<br>/g;
		#print $dump;
	#print hr;
}
my @result=();
#--- AND
#print "param(qany_or_all):", param('qany_or_all'), "<br>";
if (param('qany_or_all') eq "match ALL expressions") {
	#--- 1st run: count all occurrences of results
	my %count=();
	for (my $i=1;$i<param('nqueries');$i++) {
		if (param('qtype') eq "host") {
			for (my $j=0;$j<=$#{$q[$i]};$j++) {
				$count{$q[$i][$j]->{host_name}}++;
				#print $q[$i][$j]->{host_name}.":".$count{$q[$i][$j]->{host_name}}."<br>";
			}
		} else {
			for (my $j=0;$j<=$#{$q[$i]};$j++) {
				$count{$q[$i][$j]->{host_name}."_".$q[$i][$j]->{service_description}}++;
				#print $q[$i][$j]->{host_name}."_".$q[$i][$j]->{service_description}.":".$count{$q[$i][$j]->{host_name}."_".$q[$i][$j]->{service_description}}."<br>";
			}
		}
	}
	#--- 2nd run: only copy result to target array if if occurred in ALL query results
	for (my $j=0;$j<$#{$q[0]};$j++) {
		if (param('qtype') eq "host") {
			push @result, $q[0][$j] if ($count{$q[0][$j]->{host_name}} == param('nqueries')-1);
		} else {
			push @result, $q[0][$j] if ($count{$q[0][$j]->{host_name}."_".$q[0][$j]->{service_description}} == param('nqueries')-1);
		}
	}
#--- OR (covers also queries with one expression)
} else {
	my %count=();
	for (my $i=0;$i<param('nqueries');$i++) {
		for (my $j=0;$j<=$#{$q[$i]};$j++) {
			#--- only copy ONE occurence of package to target array
			if (param('qtype') eq "host") {
				#print "pushing $q[$i][$j]->{host_name}<br>";
				push @result, $q[$i][$j] if (!defined($count{$q[$i][$j]->{host_name}}));
				$count{$q[$i][$j]->{host_name}}++;
			} else {
				#print "pushing $q[$i][$j]->{host_name}_$q[$i][$j]->{service_description}<br>";
				push @result, $q[$i][$j] if (!defined($count{$q[$i][$j]->{host_name}."_".$q[$i][$j]->{service_description}}));
				$count{$q[$i][$j]->{host_name}."_".$q[$i][$j]->{service_description}}++;
			}
		}
	}
}
#--- at last: sort the results
#--- 1. hosts
@result=sort { $a->{host_name} cmp $b->{host_name} } @result;

#--- 2. fields from last to first
for (my $i=param('nqueries');$i>=0;$i--){
	#print "sort_order:" . param('sort_order')."<br>";
	if (param('sort_order')==1) {
		#--- string comparison
		if ($ftype[$i] eq "STRING") {
			@result=sort {uc($a->{param('qfield'.$i)}) cmp uc($b->{param('qfield'.$i)})} @result;
		#--- numeric or timestamp comparison
		} else {
			@result=sort {$a->{param('qfield'.$i)} <=> $b->{param('qfield'.$i)}} @result;
		}
	} else {
		#--- string comparison
		if ($ftype[$i] eq "STRING") {
			@result=sort {uc($b->{param('qfield'.$i)}) cmp uc($a->{param('qfield'.$i)})} @result;
		#--- numeric or timestamp comparison
		} else {
			@result=sort {$b->{param('qfield'.$i)} <=> $a->{param('qfield'.$i)}} @result;
		}
	}
}


#--- print query stats, and URL for saving query
print sup;
printf "%d results in %.2fs - ", $#result+1, time-$starttime;
print "bookmark this URL to save the query: ";
printf "<A HREF=%s>Query %s %s %s %s ", 
	url(-path_info=>1,-query=>1),
	param('qtype'),
	param('qfield0'),
	param('qop0'),
       	param('qexpr0');
for (my $i=1;$i<param('nqueries');$i++) {
	printf "%s %s %s %s ", 
		param('qany_or_all') eq "match ALL expressions" ? "AND" : "OR",
		param('qfield'.$i),
		param('qop'.$i)=~/ARRAY/ ? param_fetch('qop'.$i)->[0][0] : param('qop'.$i),
		param('qexpr'.$i);
}
print "</A>";

#--- print result table
print "<TABLE CLASS='status'>";
print "<TR align='left'>";
print "<TH class='status'>Hostname</TH>";
print "<TH class='status'>Service</TH>" if (param('qtype') eq "service");
print "<TH class='status'>State</TH>";
for (my $i=0,my %shown=();$i<param('nqueries');$i++) {
	if (!$shown{param('qfield'.$i)}) {
		if (param('qfield'.$i) ne "plugin_output") {
			#--- replace '_' by ' ' to provide header wrapping
			my $field_name=param('qfield'.$i); $field_name=~s/_/ /g;
			print "<TH class='status'>" . $field_name;
			#print "<TH class='status'>" . param('qfield'.$i);
			my $querystring=url(-path_info=>1,-query=>1);
			$querystring=~s/;sort_order=[01]//g;
			print "<A HREF='".$querystring.";sort_order=0;"."'><IMG SRC='/nagios/images/down.gif' BORDER=0'>";
			print "<A HREF='".$querystring.";sort_order=1;"."'><IMG SRC='/nagios/images/up.gif' BORDER=0'>";
			print "</TH>";
		}
		$shown{param('qfield'.$i)}++;
	}
}
print "<TH class='status'>Plugin Output</TH>";
print "</TR>";
#--- loop over items
my $previous_host="";
foreach my $item (@result) {
	my $state=$st[$item->{current_state}];
	my $fg=$fg[$item->{current_state}];
	my $bg=$bg[$item->{current_state}];
	print  "<TR>";

	#--- 1. if host changes, print host link
	# http://localhost/nagios/cgi-bin/extinfo.cgi?type=1&host=localhost
	if ($item->{host_name} ne $previous_host) {
		print "<TD CLASS='statusEven'>";
		#print "<A HREF=", $CGI_BIN, "extinfo.cgi?type=1&host=", $item->{host_name}, ">", $item->{host_name};
		printf "<A HREF=%s/extinfo.cgi?type=1&host=%s>%s", $CGI_BIN,$item->{host_name},$item->{host_name};
		$previous_host=$item->{host_name};
	} else {
		print "<TD>";
	}
	print "</TD>";

	#--- 2. print service description if service query
	# http://localhost/nagios/cgi-bin/extinfo.cgi?type=2&host=localhost&service=Embedded%20Perl%20Check
	if (param('qtype') eq "service") {
		print "<TD CLASS='status$bg'>";
		printf "<A HREF=%s/extinfo.cgi?type=2&host=%s&service=%s>%s",$CGI_BIN,$item->{host_name},
			escape($item->{service_description}),$item->{service_description};
		print "</TD>";
	}
	
	#--- 3. print state
	print "<TD CLASS='status$fg'>", $state, "</TD>";

	#--- 4. print query field
	for (my $i=0,my %shown=();$i<param('nqueries');$i++) {
		if (param('qfield'.$i) ne "plugin_output") {
			if (!$shown{param('qfield'.$i)}) {
				printf "<TD CLASS=\'status$bg\' align=%s title=%s>%s</TD>", 
					($ftype[$i] eq "STRING") ? "left" : "right",
					#($ftype[$i] eq "TIMESTAMP") ? sprintf("title=\'%s\'",timestamp($item->{param('qfield'.$i)})) : "", 
					$item->{param('qfield'.$i)},
					($ftype[$i] eq "TIMESTAMP") ? sprintf("%s",timestamp($item->{param('qfield'.$i)})) : $item->{param('qfield'.$i)}; 
				$shown{param('qfield'.$i)}++;
			}
		}
	}

	#--- 5. print plugin_output anyway
	print "<TD CLASS='status$bg'>", $item->{plugin_output}, "</TD>";

	print "</TR>";

}
print "</TABLE>";
print hr;
print "<object data='../query_examples.html' width='100%' height=768>";
print "<p>Either your browser does not support object data or you did not copy the query_examples.html into /path/to/nagios/share.<p>You can see the embedded page <a href='../query_examples.html'>query_examples.html here</a>.";
print "</object>";
print end_html;
alarm(0);

#---
#--- print nagios like timestamp
#--- 03-28-2009 18:33:29
#---
sub timestamp {
	my ($timestamp)=shift;
	my @t=localtime($timestamp);
	return sprintf "%02d-%02d-%04d %02d:%02d:%02d", 
		$t[4]+1,$t[3],$t[5]+1900,$t[2],$t[1],$t[0];
}
#---
#--- get fields from status.dat
#---
sub get_fields {
	my ($type)=@_;
	open(DAT,$STATUSDAT) || die "Cannot open $STATUSDAT:$!";
	while (<DAT>) {
		if (/^${type}status \{$/) {
			my %r=();
			while (<DAT>) {
				last if (/^\t\}$/);
				if (/\t([^=]+)=(.*)$/) {
					my $f=$1;
					$r{"$f"}++;
				}
			}
			close DAT;
			return sort keys(%r);
		}
	}
}

sub get_field_type {
	my ($type,$field)=@_;
	#print "get_field_type - type:$type field:$field field_type:".$$statusfields{$type}{$field}."<br>";
	#--- no field defined: then default setting 'plugin_output' -> "STRING" is set.
	if ($field eq "") {
		return "STRING";
	#--- found field type? then return it
	} elsif (defined($$statusfields{$type}{$field})) {
		return $$statusfields{$type}{$field};
	#--- nothing found: return UNKNOWN
	} else {
		return "UNKNOWN";
	}
}
#---
#--- get field_type from status.dat
#---
sub get_field_type_old {
	my ($type,$field)=@_;
	#print " DEBUG: looking for field:$field type:$type<br> ";
	open(DAT,$STATUSDAT) || die "Cannot open $STATUSDAT:$!";
	while (<DAT>) {
		if (/^${type}status \{$/) {
			while (<DAT>) {
				last if (/^\t\}$/);
				if (/\t$field=(\S+)$/ && $1 ne "0") {
					close DAT;
					#print " field:$field content:>$1< ";
					if ($1=~/^([\d\.]+)$/) {
						if ($1=~/^(\d{10})$/) {
							# print " TIMESTAMP:>", timestamp(time), "<";
							return "TIMESTAMP";
						} else {
							return "NUMERICAL";
						}
					} elsif ($1=~/\D+/) {
						return "STRING";
					} else {
						return "UNKNOWN";
					}
				}
			}
		}
	}
	return "UNKNOWN";
}

#---
#--- perform query from status.dat
#---
sub get_status {
	my ($type,$field,$operator,$expr)=@_;
	return () if ($type eq "" || $field eq "" || $operator eq "" || $expr eq "");
	my @result=();
	open(DAT,$STATUSDAT) || die "Cannot open $STATUSDAT:$!";
	while (<DAT>) {
		chomp;
		next if (/^#/);
		next if (/^$/);
		if (/^${type}status \{$/) {
			my $found=0;
			my %r=();
			while (<DAT>) {
				chomp;
				last if (/^\t\}$/);
				if (/\t([^=]+)=(.*)$/) {
					my $f=$1;
					my $v=$2;
					#print "f:>$f< v:>$v<\n";
					$r{"$f"}=$v;
					if ($f=~/^$field$/ && $v ne "") {
						my $expression="";
						if ($operator=~/\~/) {
							$v=~s/\'/\\'/g;
							$expression="\'${v}\'${operator}/${expr}/i";
						} elsif ($operator=~/ne|eq/) {
							$v=~s/\'/\\'/g;
							$expression="\'${v}\'${operator}\'${expr}\'";
						} else {
							$expression="${v}${operator}${expr}";
						}
						#print "expression:$expression<p>\n";
						my $e=eval "($expression)";
                				print i,"Evaluation error in \'$expression\': $@<p>" if ($@);
						if ($e) {
							$found=1;
							#print "found: $v <-> $expr<p>";
						} else {
							$found=0;
							while (<DAT>) {
			                               		last if (/\t\}$/);
                       					}
							last;
						}

					}
				} else {
					print "Invalid format: >$_<\n";
				}
			}
			if ($found) {
				#print "pushed $r{host_name}-$r{service_description}<p>\n";
				push @result,\%r;
			}
		} else {
			#print "Skipping >$line< (!=$type)...\n";
			while (<DAT>) {
				last if (/^\t\}$/);
			}
		}
	}
	close DAT;
	@result;
}