summaryrefslogtreecommitdiffstats
path: root/library/nagvis-includes/GlobalBackendicingaweb2.php
blob: 1168e0a1e5c34b8857f1507d5f91ae8d03285c72 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
<?php

class GlobalBackendicingaweb2 implements GlobalBackendInterface {
    private $CONN;
    private $backendId;
    private $dbName;
    private $dbUser;
    private $dbPass;
    private $dbHost;
    private $dbPrefix;
    private $dbInstanceName;
    private $dbInstanceId;
    private $objConfigType;

    private $hostCache;
    private $serviceCache;
    private $hostAckCache;

    // Define the backend local configuration options
    private static $validConfig = Array(
        'dbhost' => Array('must' => 1,
            'editable' => 1,
            'default' => 'localhost',
            'match' => MATCH_STRING_NO_SPACE),
        'dbport' => Array('must' => 0,
            'editable' => 1,
            'default' => '3306',
            'match' => MATCH_INTEGER),
        'dbname' => Array('must' => 1,
            'editable' => 1,
            'default' => 'nagios',
            'match' => MATCH_STRING_NO_SPACE),
        'dbuser' => Array('must' => 1,
            'editable' => 1,
            'default' => 'root',
            'match' => MATCH_STRING_NO_SPACE),
        'dbpass' => Array('must' => 0,
            'editable' => 1,
            'default' => '',
            'match' => MATCH_STRING_EMPTY),
        'dbprefix' => Array('must' => 0,
            'editable' => 1,
            'default' => 'nagios_',
            'match' => MATCH_STRING_NO_SPACE_EMPTY),
        'dbinstancename' => Array('must' => 0,
            'editable' => 1,
            'default' => 'default',
            'match' => MATCH_STRING_NO_SPACE),
        'maxtimewithoutupdate' => Array('must' => 0,
            'editable' => 1,
            'default' => '180',
            'match' => MATCH_INTEGER));

    /**
     * Constructor
     * Reads needed configuration parameters, connects to the Database
     * and checks that Nagios is running
     *
     * @param	config $MAINCFG
     * @param	String $backendId
     * @author	Andreas Husch <downanup@nagios-wiki.de>
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function __construct($backendId) {
        $this->backendId = $backendId;

        $this->hostCache = Array();
        $this->serviceCache = Array();
        $this->hostAckCache = Array();

        $this->dbName = cfg('backend_'.$backendId, 'dbname');
        $this->dbUser = cfg('backend_'.$backendId, 'dbuser');
        $this->dbPass = cfg('backend_'.$backendId, 'dbpass');
        $this->dbHost = cfg('backend_'.$backendId, 'dbhost');
        $this->dbPort = cfg('backend_'.$backendId, 'dbport');
        $this->dbPrefix = cfg('backend_'.$backendId, 'dbprefix');
        $this->dbInstanceName = cfg('backend_'.$backendId, 'dbinstancename');

        if($this->checkMysqlSupport() && $this->connectDB()) {
            // Set the instanceId
            $this->dbInstanceId = $this->getInstanceId();

            // Do some checks to make sure that Nagios is running and the Data at the DB is ok
            $QUERYHANDLE = $this->mysqlQuery('SELECT is_currently_running, UNIX_TIMESTAMP(status_update_time) AS status_update_time FROM '.$this->dbPrefix.'programstatus WHERE instance_id='.$this->dbInstanceId);
            $nagiosstate = mysql_fetch_array($QUERYHANDLE);

            // Free memory
            mysql_free_result($QUERYHANDLE);

            // Check that Nagios reports itself as running
            if ($nagiosstate['is_currently_running'] != 1) {
                throw new BackendConnectionProblem(l('nagiosNotRunning', Array('BACKENDID' =>$this->backendId)));
            }

            // Be suspicious and check that the data at the db is not older that "maxTimeWithoutUpdate" too
            if($_SERVER['REQUEST_TIME'] - $nagiosstate['status_update_time'] > cfg('backend_'.$backendId, 'maxtimewithoutupdate')) {
                throw new BackendConnectionProblem(l('nagiosDataNotUpToDate', Array('BACKENDID' => $this->backendId, 'TIMEWITHOUTUPDATE' => cfg('backend_'.$backendId, 'maxtimewithoutupdate'))));
            }

            /**
             * It looks like there is a problem with the config_type value at some
             * installations. The NDO docs and mailinglist say that the flag
             * config_type marks the objects as being read from retention data or read
             * from configuration. Until NagVis 1.3b3 only objects with config_type=1
             * were queried.
             * Cause of some problem reports that there are NO objects with
             * config_type=1 in the DB this check was added. If there is at least one
             * object with config_type=1 NagVis only recognizes objects with that
             * value set. If there is no object with config_type=1 all objects with
             * config_type=0 are recognized.
             *
             * http://www.nagios-portal.de/wbb/index.php?page=Thread&threadID=9269
             */
             if($this->checkConfigTypeObjects()) {
                 $this->objConfigType = 1;
             } else {
                 $this->objConfigType = 0;
             }
        } else {
            return FALSE;
        }

        return TRUE;
    }

    /**
     * PUBLIC Method getValidConfig
     *
     * Returns the valid config for this backend
     *
     * @return	Array
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public static function getValidConfig() {
        return self::$validConfig;
    }

    /**
     * PUBLIC Method getObjects
     *
     * Return the objects configured at Nagios which are matching the given pattern.
     * This is needed for WUI, e.g. to populate drop down lists.
     *
     * @param	string $type, string $name1Pattern, string $name2Pattern
     * @return	array $ret
     * @author	Lars Michelsen <lars@vertical-visions.de>
     * @author	Andreas Husch <downanup@nagios-wiki.de>
     */
    public function getObjects($type,$name1Pattern='',$name2Pattern='') {
        $ret = Array();
        $filter = '';
        $query = $this->backend->select();
        switch($type) {
            case 'host':
                $query->from('hostStatus', array(
                    'name1' => 'host_name'
                ));
                $objectType = 1;
                if($name1Pattern != '') {
                    $filter = ' name1=\''.$name1Pattern.'\' AND ';
                }
            break;
            case 'service':
                $objectType = 2;

                if($name1Pattern != '' && $name2Pattern != '') {
                    $filter = ' name1=\''.$name1Pattern.'\' AND name2=\''.$name2Pattern.'\' AND ';
                } else if($name1Pattern != '') {
                    $filter = ' name1=\''.$name1Pattern.'\' AND ';
                }
            break;
            case 'hostgroup':
                $objectType = 3;

                if($name1Pattern != '') {
                    $filter = ' name1=\''.$name1Pattern.'\' AND ';
                }
            break;
            case 'servicegroup':
                $objectType = 4;

                if($name1Pattern != '') {
                    $filter = ' name1=\''.$name1Pattern.'\' AND ';
                }
            break;
            default:
                return Array();
            break;
        }

        /**
         * is_active default value is 0.
         * When broker option is -1 or BROKER_RETENTION_DATA is activated the
         * current objects have is_active=1 and the deprecated object have
         * is_active=0. Workaround: Check if there is any is_active=1, then use the
         * is_active filter.
         *
         * For details see:
         * https://sourceforge.net/tracker/index.php?func=detail&aid=1839631&group_id=132019&atid=725179
         * http://www.nagios-portal.de/forum/thread.php?postid=59971#post59971
         */
        if($this->checkForIsActiveObjects()) {
            $isActiveFilter = ' is_active=1 AND';
        } else {
            $isActiveFilter = '';
        }

        $QUERYHANDLE = $this->mysqlQuery('SELECT name1,name2 FROM '.$this->dbPrefix.'objects WHERE objecttype_id='.$objectType.' AND '.$filter.$isActiveFilter.' instance_id='.$this->dbInstanceId.' ORDER BY name1');
        while($data = mysql_fetch_array($QUERYHANDLE)) {
            $ret[] = Array('name1' => $data['name1'],'name2' => $data['name2']);
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $ret;
    }

    /**
     * PUBLIC Method getObjectsEx
     *
     * Return all objects configured at Nagios plus some additional information.
     * This is needed for gmap, e.g. to populate lists.
     *
     * @param	string $type
     * @return	array $ret
     * @author	Roman Kyrylych <rkyrylych@op5.com>
     */
    public function getObjectsEx($type) {
        $ret = Array();

        return $ret;
    }

    /**
     * PRIVATE Method checkForIsActiveObjects
     *
     * Checks if there are some object records with is_active=1
     *
     * @return	Boolean
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    private function checkForIsActiveObjects() {
        if(mysql_num_rows($this->mysqlQuery('SELECT object_id FROM '.$this->dbPrefix.'objects WHERE is_active=1')) > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * PRIVATE Method checkConfigTypeObjects
     *
     * Checks if there are some object records with config_type=1
     *
     * @return	Boolean
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    private function checkConfigTypeObjects() {
        if(mysql_num_rows($this->mysqlQuery('SELECT host_id FROM '.$this->dbPrefix.'hosts WHERE config_type=1 AND instance_id='.$this->dbInstanceId.' LIMIT 1')) > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * PRIVATE parseFilter()
     *
     * Parses the filter array to backend
     *
     * @param   Array     List of objects to query
     * @param   Array     List of filters to apply
     * @param   String    Table to use for filtering
     * @param   Boolean   Split the filter by options
     * @return  String    Parsed filters
     * @author  Lars Michelsen <lars@vertical-visions.de>
     */
    private function parseFilter($objects, $filters, $table, $childTable, $isMemberQuery = false,
                                           $isCountQuery = false, $isHostQuery = true) {
        $aFilters = Array();
        foreach($objects AS $OBJS) {
            $objFilters = Array();
            foreach($filters AS $filter) {
                // Array('key' => 'host_name', 'operator' => '=', 'name'),
                switch($filter['key']) {
                    case 'host_name':
                    case 'host_groups':
                    case 'service_groups':
                    case 'hostgroup_name':
                    case 'group_name':
                    case 'groups':
                    case 'servicegroup_name':
                    case 'service_description':
                        if($filter['key'] != 'service_description')
                            $val = $OBJS[0]->getName();
                        else
                            $val = $OBJS[0]->getServiceDescription();

                        // Translate field names
                        if($filter['key'] == 'service_description')
                            $filter['key'] = 'name2';
                        else
                            $filter['key'] = 'name1';

                        if($filter['op'] == '>=')
                            $filter['op'] = '=';

                        $objFilters[] = ' '.$table.'.'.$filter['key']." ".$filter['op']." binary '".$val."' ";
                    break;
                    default:
                        throw new BackendConnectionProblem('Invalid filter key ('.$filter['key'].')');
                    break;
                }
            }

            // Are there child exclude filters defined for this object?\
            // The objTupe is the type of the objects to query the data for
            if($isMemberQuery && $OBJS[0]->hasExcludeFilters($isCountQuery)) {
                $filter = $OBJS[0]->getExcludeFilter($isCountQuery);
                $objType = $OBJS[0]->getType();

                if($objType == 'host') {
                    $parts = explode('~~', $filter);
                    if(!isset($parts[1]))
                        $objFilters[] = " ".$childTable.".name2 NOT REGEXP BINARY \"".$filter."\"";

                } elseif($objType == 'hostgroup' && $isHostQuery) {
                    $parts = explode('~~', $filter);
                    if(!isset($parts[1]))
                        $objFilters[] = " ".$childTable.".name1 NOT REGEXP BINARY \"".$parts[0]."\"";

                } elseif(($objType == 'hostgroup' && !$isHostQuery) || $objType == 'servicegroup') {
                    $parts = explode('~~', $filter);
                    if(isset($parts[1]))
                        $objFilters[] = " NOT (".$childTable.".name1 REGEXP BINARY \"".$parts[0]."\" "
                                       ." AND ".$childTable.".name2 REGEXP BINARY \"".$parts[1]."\")";
                    else
                        $objFilters[] = " ".$childTable.".name1 NOT REGEXP BINARY \"".$parts[0]."\"";
                }
            }

            $aFilters[] = implode(' AND ', $objFilters);
        }

        return implode(' OR ', $aFilters);
    }


    /**
     * PRIVATE Method getHostAckByHostname
     *
     * Returns if a host state has been acknowledged. The method doesn't check
     * if the host is in OK/DOWN, it only checks the has_been_acknowledged flag.
     *
     * @param	string $hostName
     * @return	bool $ack
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    private function getHostAckByHostname($hostName) {
        $return = 0;

        // Read from cache or fetch from NDO
        if(isset($this->hostAckCache[$hostName])) {
            $return = $this->hostAckCache[$hostName];
        } else {
            $QUERYHANDLE = $this->mysqlQuery('SELECT problem_has_been_acknowledged
            FROM '.$this->dbPrefix.'objects AS o,'.$this->dbPrefix.'hoststatus AS h
            WHERE (o.objecttype_id=1 AND o.name1 = binary \''.$hostName.'\' AND o.instance_id='.$this->dbInstanceId.') AND h.host_object_id=o.object_id LIMIT 1');

            $data = mysql_fetch_assoc($QUERYHANDLE);

            // Free memory
            mysql_free_result($QUERYHANDLE);

            // It's unnessecary to check if the value is 0, everything not equal to 1 is FALSE
            if(isset($data['problem_has_been_acknowledged']) && $data['problem_has_been_acknowledged'] == '1') {
                $return = 1;
            } else {
                $return = 0;
            }

            // Save to cache
            $this->hostAckCache[$hostName] = $return;
        }

        return $return;
    }

    /**
     * PUBLIC getHostState()
     *
     * Returns the Nagios state and additional information for the requested host
     *
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getHostState($objects, $options, $filters, $isMemberQuery = false) {
        $arrReturn = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT
            o.object_id, alias, display_name, address, o.name1,
            has_been_checked,
            last_hard_state,
            UNIX_TIMESTAMP(last_hard_state_change) AS last_hard_state_change,
            UNIX_TIMESTAMP(last_state_change) AS last_state_change,
            current_state,
            output, perfdata,
            h.notes,
            problem_has_been_acknowledged,
            UNIX_TIMESTAMP(last_check) AS last_check, UNIX_TIMESTAMP(next_check) AS next_check,
            hs.state_type, hs.current_check_attempt, hs.max_check_attempts, hs.check_command,
            UNIX_TIMESTAMP(dh.scheduled_start_time) AS downtime_start, UNIX_TIMESTAMP(dh.scheduled_end_time) AS downtime_end,
            dh.author_name AS downtime_author, dh.comment_data AS downtime_data
        FROM
            '.$this->dbPrefix.'hosts AS h,
            '.$this->dbPrefix.'objects AS o
        LEFT JOIN
            '.$this->dbPrefix.'hoststatus AS hs
            ON hs.host_object_id=o.object_id
        LEFT JOIN
            '.$this->dbPrefix.'scheduleddowntime AS dh
            ON dh.object_id=o.object_id AND NOW()>dh.scheduled_start_time AND NOW()<dh.scheduled_end_time
        WHERE
            (o.objecttype_id=1 AND ('.$this->parseFilter($objects, $filters, 'o', 'o', $isMemberQuery, false, HOST_QUERY).')
             AND o.instance_id='.$this->dbInstanceId.')
            AND (h.config_type='.$this->objConfigType.' AND h.instance_id='.$this->dbInstanceId.' AND h.host_object_id=o.object_id)');

        while($data = mysql_fetch_assoc($QUERYHANDLE)) {

            // If there is a downtime for this object, save the data
            $in_downtime = 0;
            $dt_details = array(null, null, null, null);
            if(isset($data['downtime_start']) && $data['downtime_start'] != '') {
                $in_downtime = 1;
                $dt_details = array($data['downtime_author'], $data['downtime_data'],
                                    $data['downtime_start'], $data['downtime_end']);
            }

            /**
                * Only recognize hard states. There was a discussion about the implementation
                * This is a new handling of only_hard_states. For more details, see:
                * http://www.nagios-portal.de/wbb/index.php?page=Thread&threadID=8524
                *
                * Thanks to Andurin and fredy82
                */
            if($options & 1)
                if($data['state_type'] != '0')
                    $data['current_state'] = $data['current_state'];
                else
                    $data['current_state'] = $data['last_hard_state'];

            $acknowledged = 0;

            if($data['has_been_checked'] == '0' || $data['current_state'] == '') {
                $state = UNCHECKED;
                $output = l('hostIsPending', Array('HOST' => $data['name1']));
            } elseif($data['current_state'] == '0') {
                // Host is UP
                $state = UP;
                $output = $data['output'];
            } else {
                // Host is DOWN/UNREACHABLE/UNKNOWN

                $acknowledged = intval($data['problem_has_been_acknowledged']);

                // Store state and output in array
                switch($data['current_state']) {
                    case '1':
                        $state = DOWN;
                        $output = $data['output'];
                    break;
                    case '2':
                        $state = UNREACHABLE;
                        $output = $data['output'];
                    break;
                    case '3':
                        $state = UNKNOWN;
                        $output = $data['output'];
                    break;
                    default:
                        $state = UNKNOWN;
                        $output = 'GlobalBackendndomy::getHostState: Undefined state!';
                    break;
                }
            }

            $arrReturn[$data['name1']] = array(
                $state,
                $output,
                $acknowledged,
                $in_downtime,
                0, // staleness
                $data['state_type'],
                $data['current_check_attempt'],
                $data['max_check_attempts'],
                $data['last_check'],
                $data['next_check'],
                $data['last_hard_state_change'],
                $data['last_state_change'],
                $data['perfdata'],
                $data['display_name'],
                $data['alias'],
                $data['address'],
                $data['notes'],
                $data['check_command'],
                null, // custom_vars
                $dt_details[0], // downtime author
                $dt_details[1], // downtime comment
                $dt_details[2], // downtime start
                $dt_details[3], // downtime end
            );
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrReturn;
    }

    /**
     * PUBLIC getServiceState()
     *
     * Returns the state and additional information of the requested service
     *
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getServiceState($objects, $options, $filters, $isMemberQuery = false) {
        $arrReturn = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT
            o.object_id, o.name1, o.name2,
            s.display_name,
            s.notes,
            h.address,
            ss.has_been_checked, ss.last_hard_state, ss.current_state,
            UNIX_TIMESTAMP(ss.last_hard_state_change) AS last_hard_state_change,
            UNIX_TIMESTAMP(ss.last_state_change) AS last_state_change,
            ss.output, ss.perfdata, ss.problem_has_been_acknowledged,
            UNIX_TIMESTAMP(ss.last_check) AS last_check, UNIX_TIMESTAMP(ss.next_check) AS next_check,
            ss.state_type, ss.current_check_attempt, ss.max_check_attempts, ss.check_command,
            UNIX_TIMESTAMP(dh.scheduled_start_time) AS downtime_start, UNIX_TIMESTAMP(dh.scheduled_end_time) AS downtime_end,
            dh.author_name AS downtime_author, dh.comment_data AS downtime_data
            FROM
                '.$this->dbPrefix.'services AS s,
                '.$this->dbPrefix.'hosts AS h,
                '.$this->dbPrefix.'objects AS o
            LEFT JOIN
                '.$this->dbPrefix.'servicestatus AS ss
                ON ss.service_object_id=o.object_id
            LEFT JOIN
                '.$this->dbPrefix.'scheduleddowntime AS dh
                ON dh.object_id=o.object_id AND NOW()>dh.scheduled_start_time AND NOW()<dh.scheduled_end_time
            WHERE
                (o.objecttype_id=2 AND ('.$this->parseFilter($objects, $filters, 'o', 'o', $isMemberQuery, false, !HOST_QUERY).'))
                AND (s.config_type='.$this->objConfigType.' AND s.instance_id='.$this->dbInstanceId.' AND s.service_object_id=o.object_id)
                AND (h.config_type='.$this->objConfigType.' AND h.instance_id='.$this->dbInstanceId.' AND h.host_object_id=s.host_object_id)
                ');

        while($data = mysql_fetch_assoc($QUERYHANDLE)) {
            $arrTmpReturn = Array();

            if(isset($objects[$data['name1'].'~~'.$data['name2']])) {
                $specific = true;
                $key = $data['name1'].'~~'.$data['name2'];
            } else {
                $specific = false;
                $key = $data['name1'];
            }

            // If there is a downtime for this object, save the data
            $in_downtime = 0;
            $dt_details = array(null, null, null, null);
            if(isset($data['downtime_start']) && $data['downtime_start'] != '') {
                $in_downtime = 1;
                $dt_details = array($data['downtime_author'], $data['downtime_data'],
                                    $data['downtime_start'], $data['downtime_end']);
            }

            /**
                * Only recognize hard states. There was a discussion about the implementation
                * This is a new handling of only_hard_states. For more details, see:
                * http://www.nagios-portal.de/wbb/index.php?page=Thread&threadID=8524
                *
                * Thanks to Andurin and fredy82
                */
            if($options & 1)
                if($data['state_type'] != '0')
                    $data['current_state'] = $data['current_state'];
                else
                    $data['current_state'] = $data['last_hard_state'];

            $acknowledged = 0;
            if($data['has_been_checked'] == '0' || $data['current_state'] == '') {
                $state = PENDING;
                $output = l('serviceNotChecked', Array('SERVICE' => $data['name2']));
            } elseif($data['current_state'] == '0') {
                // Host is UP
                $state = OK;
                $output = $data['output'];
            } else {
                // Host is DOWN/UNREACHABLE/UNKNOWN

                /**
                    * If state is not OK (=> WARN, CRIT, UNKNOWN) and service is not
                    * acknowledged => check for acknowledged host
                    */
                if($data['problem_has_been_acknowledged'] != 1) {
                    $acknowledged = $this->getHostAckByHostname($data['name1']);
                } else {
                    $acknowledged = intval($data['problem_has_been_acknowledged']);
                }

                // Store state and output in array
                switch($data['current_state']) {
                    case '1':
                        $state = WARNING;
                        $output = $data['output'];
                    break;
                    case '2':
                        $state = CRITICAL;
                        $output = $data['output'];
                    break;
                    case '3':
                        $state = UNKNOWN;
                        $output = $data['output'];
                    break;
                    default:
                        $state = UNKNOWN;
                        $output = 'GlobalBackendndomy::getServiceState: Undefined state!';
                    break;
                }
            }

            $svc = array(
                $state,
                $output,
                $acknowledged,
                $in_downtime,
                0, // staleness
                $data['state_type'],
                $data['current_check_attempt'],
                $data['max_check_attempts'],
                $data['last_check'],
                $data['next_check'],
                $data['last_hard_state_change'],
                $data['last_state_change'],
                $data['perfdata'],
                $data['display_name'],
                $data['display_name'],
                $data['address'],
                $data['notes'],
                $data['check_command'],
                null, //custom_vars
                $dt_details[0], // dt author
                $dt_details[1], // dt data
                $dt_details[2], // dt start
                $dt_details[3], // dt end
                $data['name2']
            );

            if($specific) {
                $arrReturn[$key] = $svc;
            } else {
                if(!isset($arrReturn[$key]))
                    $arrReturn[$key] = Array();

                $arrReturn[$key][] = $svc;
            }
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrReturn;
    }

    /**
     * PUBLIC getHostMemberCounts()
     *
     * @param   Array     List of objects to query
     * @param   Array     List of filters to apply
     * @return  Array     List of states and counts
     * @author  Lars Michelsen <lars@vertical-visions.de>
     */
    public function getHostMemberCounts($objects, $options, $filters) {
        if($options & 1)
            $stateAttr = 'IF((ss.state_type = 0), ss.last_hard_state, ss.current_state)';
        else
            $stateAttr = 'ss.current_state';

        $QUERYHANDLE = $this->mysqlQuery('SELECT
            o.name1, h.alias,
            SUM(IF(ss.has_been_checked=0,1,0)) AS pending,
            SUM(IF(('.$stateAttr.'=0 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND hs.scheduled_downtime_depth=0),1,0)) AS ok,
            SUM(IF(('.$stateAttr.'=0 AND ss.has_been_checked!=0 AND (ss.scheduled_downtime_depth!=0 OR hs.scheduled_downtime_depth!=0)),1,0)) AS ok_downtime,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND hs.scheduled_downtime_depth=0 AND ss.problem_has_been_acknowledged=0 AND hs.problem_has_been_acknowledged=0),1,0)) AS warning,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND (ss.scheduled_downtime_depth!=0 OR hs.scheduled_downtime_depth!=0)),1,0)) AS warning_downtime,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND (ss.problem_has_been_acknowledged=1 OR hs.problem_has_been_acknowledged=1)),1,0)) AS warning_ack,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND hs.scheduled_downtime_depth=0) AND ss.problem_has_been_acknowledged=0 AND hs.problem_has_been_acknowledged=0,1,0)) AS critical,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND (ss.scheduled_downtime_depth!=0 OR hs.scheduled_downtime_depth!=0)),1,0)) AS critical_downtime,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND (ss.problem_has_been_acknowledged=1 OR hs.problem_has_been_acknowledged=1)),1,0)) AS critical_ack,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND hs.scheduled_downtime_depth=0 AND ss.problem_has_been_acknowledged=0 AND hs.problem_has_been_acknowledged=0),1,0)) AS unknown,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND (ss.scheduled_downtime_depth!=0 OR hs.scheduled_downtime_depth!=0)),1,0)) AS unknown_downtime,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND (ss.problem_has_been_acknowledged=1 OR hs.problem_has_been_acknowledged=1)),1,0)) AS unknown_ack
            FROM
                '.$this->dbPrefix.'hoststatus AS hs,
                '.$this->dbPrefix.'services AS s,
                '.$this->dbPrefix.'hosts AS h,
                '.$this->dbPrefix.'objects AS o
            LEFT JOIN
                '.$this->dbPrefix.'servicestatus AS ss
                ON ss.service_object_id=o.object_id
            WHERE
                (o.objecttype_id=2 AND ('.$this->parseFilter($objects, $filters, 'o', 'o', MEMBER_QUERY, COUNT_QUERY, !HOST_QUERY).'))
                AND (s.config_type='.$this->objConfigType.' AND s.instance_id='.$this->dbInstanceId.' AND s.service_object_id=o.object_id)
                AND (h.config_type='.$this->objConfigType.' AND h.instance_id='.$this->dbInstanceId.' AND h.host_object_id=s.host_object_id)
                AND (hs.host_object_id=h.host_object_id)
                GROUP BY h.host_object_id');

        $arrReturn = Array();
        while($data = mysql_fetch_assoc($QUERYHANDLE)) {
            $arrReturn[$data['name1']] = Array(
                //'details' => Array('alias' => $data['alias']),
                'counts' => Array(
                    PENDING => Array(
                        'normal' => intval($data['pending']),
                    ),
                    OK => Array(
                        'normal'   => intval($data['ok']),
                        'stale'    => 0,
                        'downtime' => intval($data['ok_downtime']),
                    ),
                    WARNING => Array(
                        'normal'   => intval($data['warning']),
                        'stale'    => 0,
                        'ack'      => intval($data['warning_ack']),
                        'downtime' => intval($data['warning_downtime']),
                    ),
                    CRITICAL => Array(
                        'normal'   => intval($data['critical']),
                        'stale'    => 0,
                        'ack'      => intval($data['critical_ack']),
                        'downtime' => intval($data['critical_downtime']),
                    ),
                    UNKNOWN => Array(
                        'normal'   => intval($data['unknown']),
                        'stale'    => 0,
                        'ack'      => intval($data['unknown_ack']),
                        'downtime' => intval($data['unknown_downtime']),
                    ),
                )
            );
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrReturn;
    }

    public function getHostgroupStateCounts($objects, $options, $filters) {
        if($options & 1)
            $stateAttr = 'IF((hs.state_type = 0), hs.last_hard_state, hs.current_state)';
        else
            $stateAttr = 'hs.current_state';

        $QUERYHANDLE = $this->mysqlQuery('SELECT
            o.name1, hg.alias,
            SUM(IF(hs.has_been_checked=0,1,0)) AS unchecked,
            SUM(IF(('.$stateAttr.'=0 AND hs.has_been_checked!=0 AND hs.scheduled_downtime_depth=0),1,0)) AS up,
            SUM(IF(('.$stateAttr.'=0 AND hs.has_been_checked!=0 AND hs.scheduled_downtime_depth!=0),1,0)) AS up_downtime,
            SUM(IF(('.$stateAttr.'=1 AND hs.has_been_checked!=0 AND hs.scheduled_downtime_depth=0 AND hs.problem_has_been_acknowledged=0),1,0)) AS down,
            SUM(IF(('.$stateAttr.'=1 AND hs.has_been_checked!=0 AND hs.scheduled_downtime_depth!=0),1,0)) AS down_downtime,
            SUM(IF(('.$stateAttr.'=1 AND hs.has_been_checked!=0 AND hs.problem_has_been_acknowledged=1),1,0)) AS down_ack,
            SUM(IF(('.$stateAttr.'=2 AND hs.has_been_checked!=0 AND hs.scheduled_downtime_depth=0 AND hs.problem_has_been_acknowledged=0),1,0)) AS unreachable,
            SUM(IF(('.$stateAttr.'=2 AND hs.has_been_checked!=0 AND hs.scheduled_downtime_depth!=0),1,0)) AS unreachable_downtime,
            SUM(IF(('.$stateAttr.'=2 AND hs.has_been_checked!=0 AND hs.problem_has_been_acknowledged=1),1,0)) AS unreachable_ack,
            SUM(IF(('.$stateAttr.'=3 AND hs.has_been_checked!=0 AND hs.scheduled_downtime_depth=0 AND hs.problem_has_been_acknowledged=0),1,0)) AS unknown,
            SUM(IF(('.$stateAttr.'=3 AND hs.has_been_checked!=0 AND hs.scheduled_downtime_depth!=0),1,0)) AS unknown_downtime,
            SUM(IF(('.$stateAttr.'=3 AND hs.has_been_checked!=0 AND hs.problem_has_been_acknowledged=1),1,0)) AS unknown_ack
            FROM
                '.$this->dbPrefix.'objects AS o,
                '.$this->dbPrefix.'hostgroups AS hg,
                '.$this->dbPrefix.'hostgroup_members AS hgm,
                '.$this->dbPrefix.'objects AS o2
            LEFT JOIN
         '.$this->dbPrefix.'hoststatus AS hs
            ON hs.host_object_id=o2.object_id
            WHERE
                (o.objecttype_id=3 AND ('.$this->parseFilter($objects, $filters, 'o', 'o2', MEMBER_QUERY, COUNT_QUERY, HOST_QUERY).')
                 AND o.instance_id='.$this->dbInstanceId.')
                AND (hg.config_type='.$this->objConfigType.' AND hg.instance_id='.$this->dbInstanceId.' AND hg.hostgroup_object_id=o.object_id)
                AND hgm.hostgroup_id=hg.hostgroup_id
                AND (o2.objecttype_id=1 AND o2.object_id=hgm.host_object_id)
            GROUP BY o.object_id');

        $arrReturn = Array();
        while($data = mysql_fetch_assoc($QUERYHANDLE)) {
            $arrReturn[$data['name1']] = Array(
                'details' => Array(ALIAS => $data['alias']),
                'counts' => Array(
                    UNCHECKED => Array(
                        'normal'    => intval($data['unchecked']),
                    ),
                    UP => Array(
                        'normal'    => intval($data['up']),
                        'stale'    => 0,
                        'downtime'  => intval($data['up_downtime']),
                    ),
                    DOWN => Array(
                        'normal'    => intval($data['down']),
                        'stale'    => 0,
                        'ack'       => intval($data['down_ack']),
                        'downtime'  => intval($data['down_downtime']),
                    ),
                    UNREACHABLE => Array(
                        'normal'    => intval($data['unreachable']),
                        'stale'    => 0,
                        'ack'       => intval($data['unreachable_ack']),
                        'downtime'  => intval($data['unreachable_downtime']),
                    ),
                ),
            );
        }

        if($options & 1)
            $stateAttr = 'IF((ss.state_type = 0), ss.last_hard_state, ss.current_state)';
        else
            $stateAttr = 'ss.current_state';

        // If recognize_services are disabled don't fetch service information
        if($options & 2)
            return $arrReturn;

        // FIXME: Does not handle host downtimes/acks
        $QUERYHANDLE = $this->mysqlQuery('SELECT
            o.name1,
            SUM(IF(ss.has_been_checked=0,1,0)) AS pending,
            SUM(IF(('.$stateAttr.'=0 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0),1,0)) AS ok,
            SUM(IF(('.$stateAttr.'=0 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth!=0),1,0)) AS ok_downtime,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND ss.problem_has_been_acknowledged=0),1,0)) AS warning,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth!=0),1,0)) AS warning_downtime,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND ss.problem_has_been_acknowledged=1),1,0)) AS warning_ack,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND ss.problem_has_been_acknowledged=0),1,0)) AS critical,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth!=0),1,0)) AS critical_downtime,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND ss.problem_has_been_acknowledged=1),1,0)) AS critical_ack,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND ss.problem_has_been_acknowledged=0),1,0)) AS unknown,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth!=0),1,0)) AS unknown_downtime,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND ss.problem_has_been_acknowledged=1),1,0)) AS unknown_ack
            FROM
                '.$this->dbPrefix.'objects AS o,
                '.$this->dbPrefix.'hostgroups AS hg,
                '.$this->dbPrefix.'hostgroup_members AS hgm,
                '.$this->dbPrefix.'services AS s,
                '.$this->dbPrefix.'objects AS o2
            LEFT JOIN
                '.$this->dbPrefix.'servicestatus AS ss
                ON ss.service_object_id=o2.object_id
            WHERE
                (o.objecttype_id=3 AND ('.$this->parseFilter($objects, $filters, 'o', 'o2', MEMBER_QUERY, COUNT_QUERY, !HOST_QUERY).')
                 AND o.instance_id='.$this->dbInstanceId.')
                AND (hg.config_type='.$this->objConfigType.' AND hg.instance_id='.$this->dbInstanceId.' AND hg.hostgroup_object_id=o.object_id)
                AND hgm.hostgroup_id=hg.hostgroup_id
                AND (s.config_type='.$this->objConfigType.' AND s.instance_id='.$this->dbInstanceId.' AND s.host_object_id=hgm.host_object_id)
                AND (o2.objecttype_id=2 AND s.service_object_id=o2.object_id)
            GROUP BY o.object_id');

        while($data = mysql_fetch_assoc($QUERYHANDLE)) {
            $arrReturn[$data['name1']]['counts'][PENDING]['normal']    = intval($data['pending']);
            $arrReturn[$data['name1']]['counts'][OK]['normal']         = intval($data['ok']);
            $arrReturn[$data['name1']]['counts'][OK]['stale']          = 0;
            $arrReturn[$data['name1']]['counts'][OK]['downtime']       = intval($data['ok_downtime']);
            $arrReturn[$data['name1']]['counts'][WARNING]['normal']    = intval($data['warning']);
            $arrReturn[$data['name1']]['counts'][WARNING]['stale']     = 0;
            $arrReturn[$data['name1']]['counts'][WARNING]['ack']       = intval($data['warning_ack']);
            $arrReturn[$data['name1']]['counts'][WARNING]['downtime']  = intval($data['warning_downtime']);
            $arrReturn[$data['name1']]['counts'][CRITICAL]['normal']   = intval($data['critical']);
            $arrReturn[$data['name1']]['counts'][CRITICAL]['stale']    = 0;
            $arrReturn[$data['name1']]['counts'][CRITICAL]['ack']      = intval($data['critical_ack']);
            $arrReturn[$data['name1']]['counts'][CRITICAL]['downtime'] = intval($data['critical_downtime']);
            $arrReturn[$data['name1']]['counts'][UNKNOWN]['normal']    = intval($data['unknown']);
            $arrReturn[$data['name1']]['counts'][UNKNOWN]['stale']     = 0;
            $arrReturn[$data['name1']]['counts'][UNKNOWN]['ack']       = intval($data['unknown_ack']);
            $arrReturn[$data['name1']]['counts'][UNKNOWN]['downtime']  = intval($data['unknown_downtime']);
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrReturn;
    }

    public function getServicegroupStateCounts($objects, $options, $filters) {
        if($options & 1)
            $stateAttr = 'IF((ss.state_type = 0), ss.last_hard_state, ss.current_state)';
        else
            $stateAttr = 'ss.current_state';

        // FIXME: Recognize host ack/downtime
        $QUERYHANDLE = $this->mysqlQuery('SELECT
            o.name1, sg.alias,
            SUM(IF(ss.has_been_checked=0,1,0)) AS pending,
            SUM(IF(('.$stateAttr.'=0 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND ss.scheduled_downtime_depth=0),1,0)) AS ok,
            SUM(IF(('.$stateAttr.'=0 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth!=0),1,0)) AS ok_downtime,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND ss.problem_has_been_acknowledged=0),1,0)) AS warning,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth!=0),1,0)) AS warning_downtime,
            SUM(IF(('.$stateAttr.'=1 AND ss.has_been_checked!=0 AND ss.problem_has_been_acknowledged=1),1,0)) AS warning_ack,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND ss.problem_has_been_acknowledged=0),1,0)) AS critical,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth!=0),1,0)) AS critical_downtime,
            SUM(IF(('.$stateAttr.'=2 AND ss.has_been_checked!=0 AND ss.problem_has_been_acknowledged=1),1,0)) AS critical_ack,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth=0 AND ss.problem_has_been_acknowledged=0),1,0)) AS unknown,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND ss.scheduled_downtime_depth!=0),1,0)) AS unknown_downtime,
            SUM(IF(('.$stateAttr.'=3 AND ss.has_been_checked!=0 AND ss.problem_has_been_acknowledged=1),1,0)) AS unknown_ack
            FROM
                '.$this->dbPrefix.'objects AS o,
                '.$this->dbPrefix.'servicegroups AS sg,
                '.$this->dbPrefix.'servicegroup_members AS sgm,
                '.$this->dbPrefix.'services AS s,
                '.$this->dbPrefix.'objects AS o2
            LEFT JOIN
                '.$this->dbPrefix.'servicestatus AS ss
                ON ss.service_object_id=o2.object_id
            WHERE
                (o.objecttype_id=4 AND ('.$this->parseFilter($objects, $filters, 'o', 'o2', MEMBER_QUERY, COUNT_QUERY, !HOST_QUERY).')
                 AND o.instance_id='.$this->dbInstanceId.')
                AND (sg.config_type='.$this->objConfigType.' AND sg.instance_id='.$this->dbInstanceId.' AND sg.servicegroup_object_id=o.object_id)
                AND sgm.servicegroup_id=sg.servicegroup_id
                AND (s.config_type='.$this->objConfigType.' AND s.instance_id='.$this->dbInstanceId.' AND s.service_object_id=sgm.service_object_id)
                AND (o2.objecttype_id=2 AND s.service_object_id=o2.object_id)
            GROUP BY o.object_id');

        $arrReturn = Array();
        while($data = mysql_fetch_assoc($QUERYHANDLE)) {
            $arrReturn[$data['name1']] = Array(
                'details' => Array(ALIAS => $data['alias']),
                'counts' => Array(
                    PENDING => Array(
                        'normal'   => intval($data['pending']),
                    ),
                    OK => Array(
                        'normal'   => intval($data['ok']),
                        'stale'    => 0,
                        'downtime' => intval($data['ok_downtime']),
                    ),
                    WARNING => Array(
                        'normal'   => intval($data['warning']),
                        'stale'    => 0,
                        'ack'      => intval($data['warning_ack']),
                        'downtime' => intval($data['warning_downtime']),
                    ),
                    CRITICAL => Array(
                        'normal'   => intval($data['critical']),
                        'stale'    => 0,
                        'ack'      => intval($data['critical_ack']),
                        'downtime' => intval($data['critical_downtime']),
                    ),
                    UNKNOWN => Array(
                        'normal'   => intval($data['unknown']),
                        'stale'    => 0,
                        'ack'      => intval($data['unknown_ack']),
                        'downtime' => intval($data['unknown_downtime']),
                    ),
                ),
            );
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrReturn;
    }

    /**
     * PUBLIC Method getHostNamesWithNoParent
     *
     * Gets all hosts with no parent host. This method is needed by the automap
     * to get the root host.
     *
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getHostNamesWithNoParent() {
        $arrReturn = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT o1.name1
        FROM
        `'.$this->dbPrefix.'objects` AS o1,
        `'.$this->dbPrefix.'hosts` AS h1
        LEFT OUTER JOIN `'.$this->dbPrefix.'host_parenthosts` AS ph1 ON h1.host_id=ph1.host_id
        WHERE o1.objecttype_id=1
        AND (h1.config_type='.$this->objConfigType.' AND h1.instance_id='.$this->dbInstanceId.' AND h1.host_object_id=o1.object_id)
        AND ph1.parent_host_object_id IS null');

        while($data = mysql_fetch_array($QUERYHANDLE)) {
            $arrReturn[] = $data['name1'];
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrReturn;
    }

    /**
     * PUBLIC getDirectParentNamesByHostName()
     *
     * Gets the names of all parent hosts. New in 1.5. Showing parent layers on
     * the automap is only possible when the backend provides this method.
     *
     * @param		String		Name of host to get the parents of
     * @return	Array			Array with hostnames
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getDirectParentNamesByHostName($hostName) {
        $aParentNames = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT o2.name1
        FROM
        `'.$this->dbPrefix.'objects` AS o1,
        `'.$this->dbPrefix.'hosts` AS h1,
        `'.$this->dbPrefix.'host_parenthosts` AS ph1,
        `'.$this->dbPrefix.'objects` AS o2
        WHERE o1.objecttype_id=1 AND o1.name1=\''.$hostName.'\'
        AND (h1.config_type='.$this->objConfigType.' AND h1.instance_id='.$this->dbInstanceId.' AND h1.host_object_id=o1.object_id)
        AND h1.host_id=ph1.host_id
        AND o2.objecttype_id=1 AND o2.object_id=ph1.parent_host_object_id');
        while($data = mysql_fetch_array($QUERYHANDLE)) {
            $aParentNames[] = $data['name1'];
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $aParentNames;
    }

    /**
     * PUBLIC Method getDirectChildNamesByHostName
     *
     * Gets the names of all child hosts
     *
     * @param		String		Name of host to get the children of
     * @return	Array			Array with hostnames
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getDirectChildNamesByHostName($hostName) {
        $arrChildNames = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT o2.name1
        FROM
        `'.$this->dbPrefix.'objects` AS o1,
        `'.$this->dbPrefix.'hosts` AS h1,
        `'.$this->dbPrefix.'host_parenthosts` AS ph1,
        `'.$this->dbPrefix.'hosts` AS h2,
        `'.$this->dbPrefix.'objects` AS o2
        WHERE o1.objecttype_id=1 AND o1.name1=\''.$hostName.'\'
        AND (h1.config_type='.$this->objConfigType.' AND h1.instance_id='.$this->dbInstanceId.' AND h1.host_object_id=o1.object_id)
        AND o1.object_id=ph1.parent_host_object_id
        AND (h2.config_type='.$this->objConfigType.' AND h2.instance_id='.$this->dbInstanceId.' AND h2.host_id=ph1.host_id)
        AND o2.objecttype_id=1 AND h2.host_object_id=o2.object_id');
        while($data = mysql_fetch_array($QUERYHANDLE)) {
            $arrChildNames[] = $data['name1'];
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrChildNames;
    }

    /**
     * PUBLIC Method getHostsByHostgroupName
     *
     * Gets all hosts of a hostgroup
     *
     * @param		String		Name of hostgroup to get the hosts of
     * @return	Array			Array with hostnames
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getHostsByHostgroupName($hostgroupName) {
        $arrReturn = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT
                o2.name1
            FROM
                '.$this->dbPrefix.'objects AS o,
                '.$this->dbPrefix.'hostgroups AS hg,
                '.$this->dbPrefix.'hostgroup_members AS hgm,
                '.$this->dbPrefix.'objects AS o2
            WHERE
                (o.objecttype_id=3 AND o.name1 = binary \''.$hostgroupName.'\' AND o.instance_id='.$this->dbInstanceId.')
                AND (hg.config_type='.$this->objConfigType.' AND hg.instance_id='.$this->dbInstanceId.' AND hg.hostgroup_object_id=o.object_id)
                AND hgm.hostgroup_id=hg.hostgroup_id
                AND (o2.objecttype_id=1 AND o2.object_id=hgm.host_object_id)');

        while($data = mysql_fetch_array($QUERYHANDLE)) {
            // Assign actual dataset to return array
            $arrReturn[] = $data['name1'];
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrReturn;
    }

    /**
     * PUBLIC Method getServicesByServicegroupName
     *
     * Gets all services of a servicegroup
     *
     * @param		String		Name of servicegroup to get the services of
     * @return	Array			Array with hostnames and service descriptions
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getServicesByServicegroupName($servicegroupName) {
        $arrReturn = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT
                o2.name1, o2.name2
            FROM
                '.$this->dbPrefix.'objects AS o,
                '.$this->dbPrefix.'servicegroups AS sg,
                '.$this->dbPrefix.'servicegroup_members AS sgm,
                '.$this->dbPrefix.'objects AS o2
            WHERE
                (o.objecttype_id=4 AND o.name1 = binary \''.$servicegroupName.'\' AND o.instance_id='.$this->dbInstanceId.')
                AND (sg.config_type='.$this->objConfigType.' AND sg.instance_id='.$this->dbInstanceId.' AND sg.servicegroup_object_id=o.object_id)
                AND sgm.servicegroup_id=sg.servicegroup_id
                AND (o2.objecttype_id=2 AND o2.object_id=sgm.service_object_id)');

        while($data = mysql_fetch_array($QUERYHANDLE)) {
            // Assign actual dataset to return array
            $arrReturn[] = Array('host_name' => $data['name1'], 'service_description' => $data['name2']);
        }

        // Free memory
        mysql_free_result($QUERYHANDLE);

        return $arrReturn;
    }

    /**
     * PUBLIC Method getServicegroupInformations
     *
     * Gets information like the alias for a servicegroup
     *
     * @param	String		    Name of servicegroup
     * @return	Array			Array with object information
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getServicegroupInformations($servicegroupName) {
        $arrReturn = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT
                o.object_id, sg.alias
            FROM
                '.$this->dbPrefix.'objects AS o,
                '.$this->dbPrefix.'servicegroups AS sg
            WHERE
                (o.objecttype_id=4 AND o.name1 = binary \''.$servicegroupName.'\' AND o.instance_id='.$this->dbInstanceId.')
                AND (sg.config_type='.$this->objConfigType.' AND sg.instance_id='.$this->dbInstanceId.' AND sg.servicegroup_object_id=o.object_id)
                LIMIT 1');

        $data = mysql_fetch_array($QUERYHANDLE);

        // Free memory
        mysql_free_result($QUERYHANDLE);

        $arrReturn['alias'] = $data['alias'];

        return $arrReturn;
    }

    /**
     * PUBLIC Method getHostgroupInformations
     *
     * Gets information like the alias for a hostgroup
     *
     * @param	String		    Name of group
     * @return	Array			Array with object information
     * @author	Lars Michelsen <lars@vertical-visions.de>
     */
    public function getHostgroupInformations($groupName) {
        $arrReturn = Array();

        $QUERYHANDLE = $this->mysqlQuery('SELECT
                o.object_id, g.alias
            FROM
                '.$this->dbPrefix.'objects AS o,
                '.$this->dbPrefix.'hostgroups AS g
            WHERE
                (o.objecttype_id=3 AND o.name1 = binary \''.$groupName.'\' AND o.instance_id='.$this->dbInstanceId.')
                AND (g.config_type='.$this->objConfigType.' AND g.instance_id='.$this->dbInstanceId.' AND g.hostgroup_object_id=o.object_id)
                LIMIT 1');

        $data = mysql_fetch_array($QUERYHANDLE);

        // Free memory
        mysql_free_result($QUERYHANDLE);

        $arrReturn['alias'] = $data['alias'];

        return $arrReturn;
    }

        /**
     * PUBLIC getDirectChildDependenciesNamesByHostName()
     *
     * @param   String   Hostname
     * @return  Array    List of hostnames
     * @author  Thibault Cohen <thibault.cohen@savoirfairelinux.com>
     */
    public function getDirectChildDependenciesNamesByHostName($hostName, $min_business_impact=false) {
        return $this->getDirectChildNamesByHostName($hostName);
    }
    
    /*  
     * PUBLIC getDirectParentNamesByHostName()
     *
     * @param   String   Hostname
     * @return  Array    List of hostnames
   * @author  Mathias Kettner <mk@mathias-kettner.de>
     * @author  Lars Michelsen <lars@vertical-visions.de>
     */
    public function getDirectParentDependenciesNamesByHostName($hostName, $min_business_impact=false) {
        return $this->getDirectParentNamesByHostName($hostName);
    }

    public function getProgramStart() {
        $QUERYHANDLE = $this->mysqlQuery('SELECT UNIX_TIMESTAMP(program_start_time) AS program_start '
                                        .'FROM '.$this->dbPrefix.'programstatus WHERE instance_id='.$this->dbInstanceId);
        $data = mysql_fetch_array($QUERYHANDLE);
        mysql_free_result($QUERYHANDLE);
        if(isset($data[0]))
            return $data[0];
        else
            return -1;
    }


}
?>