1<?php
2///////////////////////////////////////////////////////////////////////////////
3//
4// NagiosQL
5//
6///////////////////////////////////////////////////////////////////////////////
7//
8// (c) 2005-2020 by Martin Willisegger
9//
10// Project   : NagiosQL
11// Component : Visualization Class
12// Website   : https://sourceforge.net/projects/nagiosql/
13// Version   : 3.4.1
14// GIT Repo  : https://gitlab.com/wizonet/NagiosQL
15//
16///////////////////////////////////////////////////////////////////////////////////////////////
17//
18///////////////////////////////////////////////////////////////////////////////////////////////
19//
20// Class: Common visualization functions
21//
22///////////////////////////////////////////////////////////////////////////////////////////////
23//
24// Includes all functions used to display the application data
25//
26// Name: NagVisualClass
27//
28///////////////////////////////////////////////////////////////////////////////////////////////
29namespace functions;
30
31class NagVisualClass
32{
33    // Define class variables
34    private $arrSettings        = array();  // Array includes all global settings
35    private $intPageId          = 0;        // Content page ID
36    //
37    public $arrSession          = array();  // Session content
38    public $intDomainId         = 0;        // Configuration domain ID
39    public $intDataId           = 0;        // Content data ID
40    public $strErrorMessage     = '';       // String including error messages
41
42
43    // Class includes
44    /** @var MysqliDbClass */
45    public $myDBClass;                      // Database class reference
46    /** @var NagConfigClass */
47    public $myConfigClass;                  // Configuraton class reference
48    /** @var \HTML_Template_IT */
49    public $myContentTpl;                   // Content template class reference
50
51    /**
52     * NagVisualClass constructor.
53     * @param array $arrSession                 PHP Session array
54     */
55    public function __construct($arrSession)
56    {
57        if (isset($arrSession['SETS'])) {
58            // Read global settings
59            $this->arrSettings = $arrSession['SETS'];
60        }
61        if (isset($arrSession['domain'])) {
62            $this->intDomainId = $arrSession['domain'];
63        }
64        $this->arrSession = $arrSession;
65    }
66
67    /**
68     * Search for browser type
69     * @return string                           Browser String
70     */
71    public function browserCheck()
72    {
73        $strUserAgent = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_STRING);
74        // Define variables
75        $strBrowserString = 'unknown';
76        if (false !== stripos($strUserAgent, 'msie')) {
77            $strBrowserString = 'msie';
78        } elseif (false !== stripos($strUserAgent, 'firefox')) {
79            $strBrowserString = 'firefox';
80        } elseif (false !== stripos($strUserAgent, 'opera')) {
81            $strBrowserString = 'opera';
82        } elseif (false !== stripos($strUserAgent, 'chrome')) {
83            $strBrowserString = 'chrome';
84        }
85        return $strBrowserString;
86    }
87
88    /**
89     * Checks if an user has acces to an account group
90     * @param int $intGroupId                   Group ID
91     * @param string $strType                   Access type (read,write,link)
92     * @return int                              0 = access granted / 1 = no access
93     */
94    public function checkAccountGroup($intGroupId, $strType)
95    {
96        // Define variables
97        $intReturn = 0;
98        // Admin user or member og group 0 do not need permissions
99        if (($this->arrSession['userid'] != 1) && ($intGroupId != 0)) {
100            // Define variables
101            $arrDataMain  = array();
102            // Read database values
103            $strTypeValue = $this->getGroupValue($strType);
104            if ($strTypeValue != '') {
105                $strSQL    = "SELECT * FROM `tbl_lnkGroupToUser` WHERE `idMaster`=$intGroupId AND ".
106                    '`idSlave`=' .$this->arrSession['userid']." AND $strTypeValue";
107                $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrDataMain, $intDataCount);
108                if ($booReturn == false) {
109                    $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
110                }
111                if (($booReturn == false) || ($intDataCount == 0)) {
112                    $intReturn = 1;
113                }
114            }
115        }
116        return $intReturn;
117    }
118
119    /**
120     * Find out the actual position inside the menu tree and returns it as an info line
121     * @param int $intPageId                    Current content id
122     * @param string $strTop                    Label string for the root node
123     * @return string                           HTML info string
124     */
125    public function getPosition($intPageId, $strTop = '')
126    {
127        // Define variables
128        $arrData      = array();
129        $intDataCount = 0;
130        $strPosition  = '';
131        // Read database values
132        $strSQL    = 'SELECT B.`mnuName` AS `mainitem`, B.`mnuLink` AS `mainlink`, A.`mnuName` AS `subitem`, '
133            . 'A.`mnuLink` AS `sublink` FROM `tbl_menu` AS A '
134            . 'LEFT JOIN `tbl_menu` AS B ON A.`mnuTopId` = B.`mnuId` WHERE A.`mnuId`=' .$intPageId;
135        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
136        if ($booReturn == false) {
137            $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
138        } elseif ($intDataCount != 0) {
139            $strMainLink = $this->arrSettings['path']['base_url'].$arrData[0]['mainlink'];
140            $strMain     = $arrData[0]['mainitem'];
141            $strSubLink  = $this->arrSettings['path']['base_url'].$arrData[0]['sublink'];
142            $strSub      = $arrData[0]['subitem'];
143            if ($strTop != '') {
144                $strPosition .= "<a href='".$this->arrSettings['path']['base_url']."admin.php'>".$strTop. '</a> -> ';
145            }
146            if ($strMain != '') {
147                $strPosition .= "<a href='".$strMainLink."'>".translate($strMain)."</a> -> <a href='".$strSubLink."'>".
148                    translate($strSub). '</a>';
149            } else {
150                $strPosition .= "<a href='".$strSubLink."'>".translate($strSub). '</a>';
151            }
152        }
153        return $strPosition;
154    }
155
156    /**
157     * Returns any group ID with the requested access type
158     * @param string $strType                   Access type (read,write,link)
159     * @return string                           Comma separated string with group id's
160     */
161    public function getAccessGroups($strType)
162    {
163        $strReturn = '0,';
164        $arrData   = array();
165        // Admin has rights for all groups
166        if ($this->arrSession['userid'] == 1) {
167            $strSQL    = 'SELECT `id` FROM `tbl_group`';
168            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intCount);
169            if ($booReturn == false) {
170                $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
171            } elseif ($intCount != 0) {
172                foreach ($arrData as $elem) {
173                    $strReturn .= $elem['id']. ',';
174                }
175            }
176        } else {
177            $strTypeValue = $this->getGroupValue($strType);
178            $strSQL    = 'SELECT `idMaster` FROM `tbl_lnkGroupToUser` ' .
179                'WHERE `idSlave`=' . $this->arrSession['userid'] . " AND $strTypeValue";
180            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intCount);
181            if ($booReturn == false) {
182                $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
183            } elseif ($intCount != 0) {
184                foreach ($arrData as $elem) {
185                    $strReturn .= $elem['idMaster'] . ',';
186                }
187            }
188        }
189        if (substr($strReturn, -1) == ',') {
190            $strReturn = substr($strReturn, 0, -1);
191        }
192        return $strReturn;
193    }
194
195    /**
196     * Generate the main menu HTML
197     * @param int $intPageId                    Current content id
198     * @param int $intCntId                     Menu group ID
199     * @return string                           HTML menu string
200     */
201    public function getMenu($intPageId, $intCntId = 1)
202    {
203        // Define variables
204        $strQueryString = filter_input(INPUT_SERVER, 'QUERY_STRING', FILTER_SANITIZE_STRING);
205        $strPHPSelf     = filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_STRING);
206
207        // Modify URL for visible/invisible menu
208        $strQuery = str_replace(
209            array('menu=visible&', 'menu=invisible&', 'menu=visible', 'menu=invisible'),
210            '',
211            $strQueryString
212        );
213        if ($strQuery != '') {
214            $strVisible   = str_replace('&', '&amp;', $strPHPSelf. '?menu=visible&' .$strQuery);
215            $strInvisible = str_replace('&', '&amp;', $strPHPSelf. '?menu=invisible&' .$strQuery);
216        } else {
217            $strVisible   = $strPHPSelf. '?menu=visible';
218            $strInvisible = $strPHPSelf. '?menu=invisible';
219        }
220        $this->intPageId = $intPageId;
221        if (!isset($this->arrSession['menu']) || ($this->arrSession['menu'] != 'invisible')) {
222            // Menu visible
223            $strHTML  = '<td width="150" align="center" valign="top">'."\n";
224            $strHTML .= '<table cellspacing="1" class="menutable">'."\n";
225            $this->hasMenuRecursive(0, 'menu', $intCntId, $strHTML);
226            $strHTML .= '</table>'."\n";
227            $strHTML .= '<br><a href="'.$strInvisible.'" class="menulinksmall">['.translate('Hide menu').']</a>'."\n";
228            $strHTML .= '<div id="donate"><a href="http://sourceforge.net/donate/index.php?group_id=134390" ';
229            $strHTML .= 'target="_blank"><img src="'.$this->arrSettings['path']['base_url'].'images/donate_2.png" ';
230            $strHTML .= 'width="60" height="24" border="0" alt="'.translate('Donate for NagiosQL on sourceforge');
231            $strHTML .= '" title="'.translate('Donate for NagiosQL on sourceforge').'"></a></div>';
232            $strHTML .= '</td>'."\n";
233        } else {
234            // Menu invisible
235            $strHTML  = '<td valign="top">'."\n";
236            $strHTML .= '<a href="'.$strVisible.'"><img src="'.$this->arrSettings['path']['base_url'];
237            $strHTML .= 'images/menu.gif" alt="'.translate('Show menu').'" border="0" ></a>'."\n";
238            $strHTML .= '</td>'."\n";
239        }
240        return $strHTML;
241    }
242
243    /**
244     * Add security features to text values
245     * @param string $strKey                    Process string
246     * @return string                           Modified process string
247     */
248    public function tfSecure($strKey)
249    {
250        $strKey = stripslashes($strKey);
251        $strKey = $this->myDBClass->realEscape($strKey);
252        return $strKey;
253    }
254
255    /**
256     * Build a string which contains links for additional pages. This is used in data lists
257     * with more items then defined in settings "lines per page limit"
258     * @param string $strSite                   Link to page
259     * @param int $intDataCount                 Sum of all data lines
260     * @param int $chkLimit                     Actual data limit
261     * @param string $strOrderBy                OrderBy Field
262     * @param string $strOrderDir               Order direction
263     * @return string                           Page site number string (HTML)
264     */
265    public function buildPageLinks($strSite, $intDataCount, $chkLimit, $strOrderBy = '', $strOrderDir = '')
266    {
267        $intMaxLines  = $this->arrSettings['common']['pagelines'];
268        $intCount     = 1;
269        $intCheck     = 0;
270        $strReturn    = '';
271        $strSiteHTML  = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n<tr>\n<td class=\"sitenumber\" ";
272        $strSiteHTML .= 'style="padding-left:7px;padding-right:7px;">' .translate('Page').": </td>\n";
273        for ($i=0; $i<$intDataCount; $i += $intMaxLines) {
274            $strLink1 = "<a href=\"$strSite?limit=$i&amp;orderby=$strOrderBy&amp;orderdir=$strOrderDir\">";
275            $strLink2 = "onclick=\"location.href='$strSite?limit=$i&amp;orderby=$strOrderBy&amp;orderdir=".
276                "$strOrderDir'\"";
277            if ((!(($chkLimit >= ($i+($intMaxLines*5))) || ($chkLimit <= ($i-($intMaxLines*5))))) || ($i==0) ||
278                ($i>=($intDataCount-$intMaxLines))) {
279                if ($chkLimit == $i) {
280                    $strSiteHTML .= "<td class=\"sitenumber-sel\">$intCount</td>\n";
281                } else {
282                    $strSiteHTML .= "<td class=\"sitenumber\" $strLink2>".$strLink1.$intCount."</a></td>\n";
283                }
284                $intCheck = 0;
285            } elseif ($intCheck == 0) {
286                $strSiteHTML .= "<td class=\"sitenumber\">...</td>\n";
287                $intCheck = 1;
288            }
289            $intCount++;
290        }
291        $strSiteHTML .= "</tr>\n</table>\n";
292        if ($intCount > 2) {
293            $strReturn = $strSiteHTML;
294        }
295        return $strReturn;
296    }
297
298    /**
299     * Builds a simple selection field inside a template
300     * @param string $strTable                  Table name (source data)
301     * @param string $strTabField               Field name (source data)
302     * @param string $strTemplKey               Template key
303     * @param int $intModeId                    0=only data, 1=with empty line at the beginning,
304     *                                          2=with empty line and 'null' line at the beginning
305     * @param int $intSelId                     Selected data ID (from master table)
306     * @param int $intExclId                    Exclude ID
307     * @return int                              0 = successful / 1 = error
308     */
309    public function parseSelectSimple(
310        $strTable,
311        $strTabField,
312        $strTemplKey,
313        $intModeId = 0,
314        $intSelId = -9,
315        $intExclId = -9
316    ) {
317        // Define variables
318        $intOption = 0;
319        $arrData   = array();
320        $intReturn = 1;
321        // Compute option value
322        if (($strTemplKey == 'hostcommand') || ($strTemplKey == 'servicecommand')) {
323            $intOption = 1;
324        }
325        if ($strTemplKey == 'eventhandler') {
326            $intOption = 2;
327        }
328        if ($strTemplKey == 'service_extinfo') {
329            $intOption = 7;
330        }
331        // Get version
332        $this->myConfigClass->getDomainData('version', $intVersion);
333        // Get raw data
334        $booRaw = $this->getSelectRawdata($strTable, $strTabField, $arrData, $intOption);
335        if ($booRaw == 0) {
336            // Insert an empty line in mode 1
337            if (($intModeId == 1) || ($intModeId == 2)) {
338                $this->myContentTpl->setVariable('SPECIAL_STYLE', '');
339                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), '&nbsp;');
340                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey).'_ID', 0);
341                if ($intVersion < 3) {
342                    $this->myContentTpl->setVariable('VERSION_20_MUST', 'inpmust');
343                }
344                $this->myContentTpl->parse($strTemplKey);
345            }
346            // Insert a 'null' line in mode 2
347            if ($intModeId == 2) {
348                $this->myContentTpl->setVariable('SPECIAL_STYLE', '');
349                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), 'null');
350                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey).'_ID', -1);
351                if ($intVersion < 3) {
352                    $this->myContentTpl->setVariable('VERSION_20_MUST', 'inpmust');
353                }
354                if ($intSelId == -1) {
355                    $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey). '_SEL', 'selected');
356                }
357                $this->myContentTpl->parse($strTemplKey);
358            }
359            // Insert data sets
360            foreach ($arrData as $elem) {
361                $this->myContentTpl->setVariable('SPECIAL_STYLE', '');
362                if ($elem['key'] == $intExclId) {
363                    continue;
364                }
365                if (isset($elem['active']) && $elem['active'] == 0) {
366                    $strActive=' [inactive]';
367                    $this->myContentTpl->setVariable('SPECIAL_STYLE', 'inactive_option');
368                } else {
369                    $strActive = '';
370                }
371                if (isset($elem['config_id']) && $elem['config_id'] == 0) {
372                    $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), htmlspecialchars(
373                            $elem['value'],
374                            ENT_QUOTES,
375                            'UTF-8'
376                        ).' [common]'.$strActive);
377                } else {
378                    $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), htmlspecialchars(
379                            $elem['value'],
380                            ENT_QUOTES,
381                            'UTF-8'
382                        ).$strActive);
383                }
384                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey). '_ID', $elem['key']);
385                if ($intVersion < 3) {
386                    $this->myContentTpl->setVariable('VERSION_20_MUST', 'inpmust');
387                }
388                if ($intSelId == $elem['key']) {
389                    $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey). '_SEL', 'selected');
390                }
391                $this->myContentTpl->parse($strTemplKey);
392            }
393            $intReturn = 0;
394        }
395        return $intReturn;
396    }
397
398    /**
399     * Builds a multi selection field inside a template
400     * @param string $strTable                  Table name (source data)
401     * @param string $strTabField               Field name (source data)
402     * @param string $strTemplKey               Template key
403     * @param string $strLinkTable              Name of link table
404     * @param int $intModeId                    0 = only data
405     *                                          1 = with empty line at the beginning
406     *                                          2 = with * line at the beginning
407     * @param int $intTypeId                    Type ID (from master table)
408     * @param int $intExclId                    Exclude ID
409     * @param string $strRefresh                Session token for refresh mode
410     * @return int                              0 = successful / 1 = error
411     */
412    public function parseSelectMulti(
413        $strTable,
414        $strTabField,
415        $strTemplKey,
416        $strLinkTable,
417        $intModeId = 0,
418        $intTypeId = -9,
419        $intExclId = -9,
420        $strRefresh = ''
421    ) {
422        // Compute option value
423        $intOption      = 2;
424        $intRefresh     = 0;
425        $intReturn      = 1;
426        $arrSelectedAdd = array();
427        $arrData        = array();
428        $booSelAdd      = false;
429        if ($strLinkTable == 'tbl_lnkServicegroupToService') {
430            $intOption = 3;
431        }
432        if ($strLinkTable == 'tbl_lnkServicedependencyToService_DS') {
433            $intOption = 4;
434        }
435        if ($strLinkTable == 'tbl_lnkServicedependencyToService_S') {
436            $intOption = 5;
437        }
438        if ($strLinkTable == 'tbl_lnkServiceescalationToService') {
439            $intOption = 6;
440        }
441        if ($strTemplKey  == 'host_services') {
442            $intOption = 8;
443        }
444        if ($strTemplKey  == 'service_parents') {
445            $intOption = 9;
446        }
447        if (($strLinkTable == 'tbl_lnkServiceToService') || ($strLinkTable == 'tbl_lnkServicetemplateToService')) {
448            $intOption = 10;
449        }
450        // Get version
451        $this->myConfigClass->getDomainData('version', $intVersion);
452        // Get raw data
453        $booRaw = $this->getSelectRawdata($strTable, $strTabField, $arrData, $intOption);
454        // Get selected data
455        $booSel = $this->getSelectedItems($strLinkTable, $arrSelected, $intOption);
456        // Get additional selected data
457        if ($strLinkTable == 'tbl_lnkHostToHostgroup') {
458            $booSelAdd = $this->getSelectedItems('tbl_lnkHostgroupToHost', $arrSelectedAdd, 8);
459        }
460        if ($strLinkTable == 'tbl_lnkHostgroupToHost') {
461            $booSelAdd = $this->getSelectedItems('tbl_lnkHostToHostgroup', $arrSelectedAdd, 8);
462        }
463        // Get browser
464        $strBrowser = $this->browserCheck();
465        // Refresh processing (replaces selection array)
466        if ($strRefresh != '' && isset($this->arrSession['refresh']) &&
467            isset($this->arrSession['refresh'][$strRefresh]) &&
468            \is_array($this->arrSession['refresh'][$strRefresh])) {
469            $arrSelected = $this->arrSession['refresh'][$strRefresh];
470            $intRefresh  = 1;
471            $booSel      = 0;
472        }
473        if ($booRaw == 0) {
474            $intCount = 0;
475            // Insert an empty line in mode 1
476            if ($intModeId == 1) {
477                $this->myContentTpl->setVariable('SPECIAL_STYLE', '');
478                $this->myContentTpl->setVariable('OPTION_DISABLED', '');
479                if (($strBrowser == 'msie') && ($this->arrSettings['common']['seldisable'] != 0)) {
480                    $this->myContentTpl->setVariable('OPTION_DISABLED', 'disabled="disabled"');
481                }
482                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), '&nbsp;');
483                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey).'_ID', 0);
484                if ($intVersion < 3) {
485                    $this->myContentTpl->setVariable('VERSION_20_MUST', 'inpmust');
486                }
487                $this->myContentTpl->parse($strTemplKey);
488                $intCount++;
489            }
490            // Insert an * line in mode 2
491            if ($intModeId == 2) {
492                $this->myContentTpl->setVariable('SPECIAL_STYLE', '');
493                $this->myContentTpl->setVariable('OPTION_DISABLED', '');
494                if (($strBrowser == 'msie') && ($this->arrSettings['common']['seldisable'] != 0)) {
495                    $this->myContentTpl->setVariable('OPTION_DISABLED', 'disabled="disabled"');
496                }
497                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), '*');
498                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey).'_ID', '*');
499                if ($intVersion < 3) {
500                    $this->myContentTpl->setVariable('VERSION_20_MUST', 'inpmust');
501                }
502                if ($intTypeId  == 2) {
503                    $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey). '_SEL', 'selected');
504                }
505                if (($intRefresh == 1) && \in_array('*', $arrSelected, true)) {
506                    $this->myContentTpl->setVariable('DAT_' .strtoupper($strTemplKey). '_SEL', 'selected');
507                    $this->myContentTpl->setVariable('IE_' .strtoupper($strTemplKey). '_SEL', 'ieselected');
508                }
509                $intCount++;
510                $this->myContentTpl->parse($strTemplKey);
511            }
512            // Insert data sets
513            foreach ($arrData as $elem) {
514                if ($elem['key'] == $intExclId) {
515                    continue;
516                }
517                if (( $intOption == 10) && (strstr($elem['key'], '-', true) == $intExclId)) {
518                    continue;
519                }
520                if ($elem['value'] == '') {
521                    continue;
522                }
523                $intIsSelected = 0;
524                $intIsExcluded = 0;
525                $intIsForeign  = 0;
526                $this->myContentTpl->setVariable('SPECIAL_STYLE', '');
527                $this->myContentTpl->setVariable('OPTION_DISABLED', '');
528                if (($strBrowser == 'msie') && ($this->arrSettings['common']['seldisable'] != 0)) {
529                    $this->myContentTpl->setVariable('OPTION_DISABLED', 'disabled="disabled"');
530                }
531                if (isset($elem['active']) && $elem['active'] == 0) {
532                    $strActive=' [inactive]';
533                    $this->myContentTpl->setVariable('SPECIAL_STYLE', 'inactive_option');
534                } else {
535                    $strActive = '';
536                }
537                if (isset($elem['config_id']) && $elem['config_id'] == 0) {
538                    $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), htmlspecialchars(
539                            $elem['value'],
540                            ENT_QUOTES,
541                            'UTF-8'
542                        ).' [common]'.$strActive);
543                } else {
544                    $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), htmlspecialchars(
545                            $elem['value'],
546                            ENT_QUOTES,
547                            'UTF-8'
548                        ).$strActive);
549                }
550                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey). '_ID', $elem['key']);
551                $this->myContentTpl->setVariable('CLASS_SEL', '');
552                if ($intVersion < 3) {
553                    $this->myContentTpl->setVariable('VERSION_20_MUST', 'inpmust');
554                }
555                if (($booSel == 0) && \in_array($elem['key'], $arrSelected, true)) {
556                    $intIsSelected = 1;
557                }
558                if (($booSel == 0) && \in_array($elem['value'], $arrSelected, true)) {
559                    $intIsSelected = 1;
560                }
561                if ($booSelAdd !== null && ($booSelAdd == 0) && \in_array($elem['key'], $arrSelectedAdd, true)) {
562                    $intIsForeign = 1;
563                }
564                if ($booSelAdd !== null && ($booSelAdd == 0) && \in_array($elem['value'], $arrSelectedAdd, true)) {
565                    $intIsForeign = 1;
566                }
567                if (($intIsForeign == 1) && ($strActive == '')) {
568                    $this->myContentTpl->setVariable('SPECIAL_STYLE', 'foreign_option');
569                }
570                // Exclude rule
571                if (($booSel == 0) && \in_array('e' . $elem['key'], $arrSelected, true)) {
572                    $intIsExcluded = 1;
573                }
574                if (($booSel == 0) && \in_array('e' . '::' . $elem['value'], $arrSelected, true)) {
575                    $intIsExcluded = 1;
576                }
577                if ($intIsExcluded == 1) {
578                    if (isset($elem['config_id']) && $elem['config_id'] == 0) {
579                        $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), '!'.
580                            htmlspecialchars($elem['value'], ENT_QUOTES, 'UTF-8').' [common]'.$strActive);
581                    } else {
582                        $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), '!'.
583                            htmlspecialchars($elem['value'], ENT_QUOTES, 'UTF-8').$strActive);
584                    }
585                    $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey). '_ID', 'e'.$elem['key']);
586                }
587                if (($intIsSelected == 1) || ($intIsExcluded == 1)) {
588                    $this->myContentTpl->setVariable('DAT_' .strtoupper($strTemplKey). '_SEL', 'selected');
589                    $this->myContentTpl->setVariable('IE_' .strtoupper($strTemplKey). '_SEL', 'ieselected');
590                }
591                $intCount++;
592                $this->myContentTpl->parse($strTemplKey);
593            }
594            if ($intCount == 0) {
595                // Insert an empty line to create valid HTML select fields
596                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), '&nbsp;');
597                $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey).'_ID', 0);
598                $this->myContentTpl->parse($strTemplKey);
599            }
600            $intReturn = 0;
601        } else {
602            // Insert an empty line to create valid HTML select fields
603            $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey), '&nbsp;');
604            $this->myContentTpl->setVariable('DAT_'.strtoupper($strTemplKey).'_ID', 0);
605            $this->myContentTpl->parse($strTemplKey);
606        }
607        return $intReturn;
608    }
609
610    /**
611     * Merge message strings and check for duplicate messages
612     * @param string $strNewMessage             Message to add
613     * @param string $strOldMessage             Modified message string (by reference)
614     * @param string $strSeparate               Separate string (<br> or \n)
615     */
616    public function processMessage($strNewMessage, &$strOldMessage, $strSeparate = '<br>')
617    {
618        $strNewMessage = str_replace(array('::::', '::'), array('::', $strSeparate), $strNewMessage);
619        if (($strOldMessage != '') && ($strNewMessage != '')) {
620            if (substr_count($strOldMessage, $strNewMessage) == 0) {
621                if (substr_count(substr($strOldMessage, -5), $strSeparate) == 0) {
622                    $strOldMessage .= $strSeparate.$strNewMessage;
623                } else {
624                    $strOldMessage .= $strNewMessage;
625                }
626            }
627        } else {
628            $strOldMessage .= $strNewMessage;
629        }
630    }
631
632    /**
633     * Returns an SQL fragment based on group access type
634     * @param string $strType                   Access type (read,write,link)
635     * @return string                           SQL fragment for group selection
636     */
637    private function getGroupValue($strType)
638    {
639        // Define variables
640        $strTypeValue = '';
641        // Select SQL by type
642        switch ($strType) {
643            case 'read':
644                $strTypeValue = "`read`='1'";
645                break;
646            case 'write':
647                $strTypeValue = "`write`='1'";
648                break;
649            case 'link':
650                $strTypeValue = "`link`='1'";
651                break;
652        }
653        return $strTypeValue;
654    }
655
656    /**
657     * Recursive function to build the main menu
658     * @param int intTopId                      ID of top menu point
659     * @param string $strCSS                    CSS class
660     * @param int $intCntId                     Menu group ID
661     * @param string $strMenuHTML               HTML menu string (by Reference)
662     * @return bool
663     */
664    private function hasMenuRecursive($intTopId, $strCSS, $intCntId, &$strMenuHTML)
665    {
666        // Define variables
667        $intLevel  = substr_count($strCSS, '_sub') + 1;
668        $booReturn = false;
669        $arrData   = array();
670        // Define SQL
671        $strSQL = 'SELECT mnuId, mnuName, mnuTopId, mnuLink FROM tbl_menu ' .
672            "WHERE mnuTopId=$intTopId AND mnuCntId=$intCntId AND mnuActive <> 0 AND ".
673            'mnuGrpId IN (' .$this->getAccessGroups('read'). ') ORDER BY mnuOrderId';
674        $booRet = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
675        if (($booRet != false) && ($intDataCount != 0)) {
676            $strTemp   = '';
677            // Menu items
678            foreach ($arrData as $elem) {
679                $strName  = translate($elem['mnuName']);
680                $strLink  = $this->arrSettings['path']['base_url'].$elem['mnuLink'];
681                $strTemp .= '  <tr>'."\n";
682                if (($elem['mnuId'] == $this->intPageId) || ($this->isMenuActive($elem['mnuId']) == true)) {
683                    $strTemp  .= '    <td class="'.$strCSS.'_act">';
684                    $strTemp  .= '<a href="'.$strLink.'">'.$strName.'</a></td>'."\n";
685                    $booReturn = true;
686                } else {
687                    $strTemp  .= '    <td class="'.$strCSS.'">';
688                    $strTemp  .= '<a href="'.$strLink.'">'.$strName.'</a></td>'."\n";
689                }
690                $strTemp .= '  </tr>'."\n";
691                // Recursive call to get submenu items
692                if ((($elem['mnuId'] == $this->intPageId) || ($this->isMenuActive($elem['mnuId']) == true)) &&
693                    $this->hasMenuRecursive($elem['mnuId'], $strCSS . '_sub', $intCntId, $strTemp) == true) {
694                    $booReturn = true;
695                }
696                if ($intTopId == $this->intPageId) {
697                    $booReturn = true;
698                }
699            }
700            if ($booReturn == true) {
701                $strMenuHTML .= $strTemp;
702            } elseif ($intLevel == 1) {
703                $strMenuHTML .= $strTemp;
704            }
705        } else {
706            $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
707        }
708        return $booReturn;
709    }
710
711    /**
712     * Check if menu point is selected
713     * @param int $intMenuId                    Menu ID
714     * @return bool                             true if active
715     */
716    public function isMenuActive($intMenuId)
717    {
718        $booReturn = false;
719        $arrData   = array();
720        $strSQL = 'SELECT mnuTopId FROM tbl_menu WHERE mnuId=' .$this->intPageId. ' AND mnuActive <> 0 ' .
721            'AND mnuGrpId IN (' .$this->getAccessGroups('read'). ')';
722        $booRet = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
723        if (($booRet != false) && ($intDataCount != 0)) {
724            foreach ($arrData as $elem) {
725                if ($elem['mnuTopId'] == $intMenuId) {
726                    $booReturn = true;
727                }
728            }
729        } else {
730            $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
731        }
732        return $booReturn;
733    }
734
735    /**
736     * Get raw table data
737     * @param string $strTable                  Data table name
738     * @param string $strTabField               Data field name
739     * @param array $arrData                    Raw data array (by reference)
740     * @param int $intOption                    Option value
741     * @return int                              0 = successful / 1 = error
742     */
743    public function getSelectRawdata($strTable, $strTabField, &$arrData, $intOption = 0)
744    {
745        // Define variables
746        $arrDataRaw   = array();
747        $intDataCount = 0;
748        $intReturn    = 0;
749        $intDouble    = 0;
750        // Get link rights
751        $strAccess = $this->getAccessGroups('link');
752        // Common domain is enabled?
753        $this->myConfigClass->getDomainData('enable_common', $intCommonEnable);
754        if ($intCommonEnable == 1) {
755            $strDomainWhere1 = ' (`config_id`=' .$this->intDomainId. ' OR `config_id`=0) ';
756            $strDomainWhere2 = ' (`tbl_service`.`config_id`=' .$this->intDomainId. ' OR `tbl_service`.`config_id`=0) ';
757        } else {
758            $strDomainWhere1 = ' `config_id`=' .$this->intDomainId. ' ';
759            $strDomainWhere2 = ' `tbl_service`.`config_id`=' .$this->intDomainId. ' ';
760        }
761        // Define SQL commands
762        if ($strTable == 'tbl_group') {
763            $strSQL = $this->getRawDataSQLGroup($strTabField);
764        } elseif (($strTable == 'tbl_configtarget') || ($strTable == 'tbl_datadomain') ||
765            ($strTable == 'tbl_language')) {
766            $strSQL = $this->getRawDataSQLDomain($strTable, $strTabField);
767        } elseif ($strTable == 'tbl_command') {
768            $strSQL = $this->getRawDataSQLCommand($strTabField, $strDomainWhere1, $strAccess, $intOption);
769        } elseif (($strTable == 'tbl_timeperiod') && ($strTabField == 'name')) {
770            $strSQL = $this->getRawDataSQLTimeperiod($strDomainWhere1, $strAccess);
771        } elseif (($strTable == 'tbl_service') && ($intOption == 3)) {
772            $strSQL = $this->getRawDataSQLService3($strDomainWhere2, $strAccess);
773            $intDouble = 1;
774        } elseif (($strTable == 'tbl_service') && (($intOption == 4) || ($intOption == 5) || ($intOption == 6))) {
775            $strSQL = $this->getRawDataSQLService456($strTabField, $intOption, $strDomainWhere1, $strAccess);
776        } elseif (($strTable == 'tbl_service') && ($intOption == 7)) {
777            if (isset($this->arrSession['refresh']) && isset($this->arrSession['refresh']['se_host'])) {
778                $intHostId = $this->arrSession['refresh']['se_host'];
779                $strSQL = $this->getRawDataSQLService7($strTabField, $strDomainWhere1, $intHostId, $strAccess);
780            } else {
781                $strSQL = '';
782            }
783        } elseif ((($strTable == 'tbl_service') || ($strTable == 'tbl_servicetemplate')) &&
784            (($intOption == 8) || ($intOption == 9))) {
785            // Service selection inside Host definition
786            $strSQL = $this->getRawDataSQLService89($strDomainWhere1, $strAccess);
787        } elseif ((($strTable == 'tbl_service') || ($strTable == 'tbl_servicetemplate')) &&
788            ($intOption == 10)) {
789            // Service selection inside Host definition
790            $strSQL = $this->getRawDataSQLService10($strDomainWhere2, $strAccess);
791        } else {
792            // Common statement
793            $strSQL = $this->getRawDataSQLCommon($strTable, $strTabField, $strDomainWhere1, $strAccess);
794        }
795        // Process data
796        if ($strSQL != '') {
797            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrDataRaw, $intDataCount);
798            if ($booReturn == false) {
799                $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
800                $intReturn = 1;
801            }
802            if ($intDouble == 1) {
803                $arrDataRawTemp = array();
804                $arrKey = array();
805                foreach ($arrDataRaw AS $elem) {
806                    if (!isset($arrKey[$elem['key']])) {
807                        $arrKey[$elem['key']] = 1;
808                        $arrDataRawTemp[] = $elem;
809                    }
810                }
811                $arrDataRaw = $arrDataRawTemp;
812            }
813        }
814        if ($strTable == 'tbl_group') {
815            $arrTemp = array();
816            $arrTemp['key']   = 0;
817            $arrTemp['value'] = translate('Unrestricted access');
818            $arrData[] = $arrTemp;
819        }
820        if (($intReturn == 0) && ($intDataCount != 0)) {
821            foreach ($arrDataRaw as $elem) {
822                $arrData[] = $elem;
823            }
824        } elseif ($strTable != 'tbl_group') {
825            $arrData = array('key' => 0, 'value' => 'no data');
826            $intReturn = 1;
827        }
828        return $intReturn;
829    }
830
831    /**
832     * Inserts the domain list to the list view template (host and services only)
833     * @param \HTML_Template_IT $resTemplate    Template object
834     */
835    public function insertDomainList($resTemplate)
836    {
837        $arrDataDomain = array();
838        $strSQL    = "SELECT * FROM `tbl_datadomain` WHERE `active` <> '0' ORDER BY `domain`";
839        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrDataDomain, $intDataCount);
840        if ($booReturn && ($intDataCount != 0)) {
841            foreach ($arrDataDomain as $elem) {
842                // Check access rights
843                if ($this->checkAccountGroup($elem['access_group'], 'read') == 0) {
844                    $resTemplate->setVariable('DOMAIN_ID', $elem['id']);
845                    $resTemplate->setVariable('DOMAIN_NAME', $elem['domain']);
846                    if ($this->intDomainId == $elem['id']) {
847                        $resTemplate->setVariable('DOMAIN_SEL', 'selected');
848                    }
849                    $resTemplate->parse('domainlist');
850                }
851            }
852        } elseif (!$booReturn) {
853            $this->strErrorMessage .= translate('Error while selecting data from database:').
854                '::' .$this->myDBClass->strErrorMessage;
855        }
856    }
857
858    /**
859     * Adds a "/" after a parh string and replaces double "//" with "/"
860     * @param string $strPath                   Path string
861     * @return string                           Modified path string
862     */
863    public function addSlash($strPath)
864    {
865        if ($strPath == '') {
866            return '';
867        }
868        $strPath .= '/';
869        while (substr_count($strPath, '//') != 0) {
870            $strPath = str_replace('//', '/', $strPath);
871        }
872        return $strPath;
873    }
874
875    ///////////////////////////////////////////////////////////////////////////////////////////
876    //  Function: Process "null" values
877    ///////////////////////////////////////////////////////////////////////////////////////////
878    //
879    //  Replaces "NULL" with -1
880    //
881    //  Parameters:                      $strKey                    Process string
882    //
883    //  Return value:                    Modified process string
884    //
885    ///////////////////////////////////////////////////////////////////////////////////////////
886    /**
887     * Replaces "NULL" with -1
888     * @param string $strKey                    Process string
889     * @return string                           Modified process string
890     */
891    public function checkNull($strKey)
892    {
893        $strReturn = $strKey;
894        if (strtoupper($strKey) == 'NULL') {
895            $strReturn = -1;
896        }
897        return $strReturn;
898    }
899
900
901    // PRIVATE functions
902
903    /**
904     * Define SQL commands for group table
905     * @param string $strTabField               Table field
906     * @return string                           SQL Statement
907     */
908    private function getRawDataSQLGroup($strTabField)
909    {
910        $strSQL = 'SELECT `id` AS `key`, `' . $strTabField . '` AS `value`, `active` ' .
911            "FROM `tbl_group` WHERE `active`='1' AND `" . $strTabField . "` <> '' ".
912            'AND `' . $strTabField . '` IS NOT NULL ORDER BY `' . $strTabField . '`';
913        return $strSQL;
914    }
915
916    /**
917     * Define SQL commands for configtarget, datadomain and language table
918     * @param string $strTable                  Table name
919     * @param string $strTabField               Table field
920     * @return string                           SQL Statement
921     */
922    private function getRawDataSQLDomain($strTable, $strTabField)
923    {
924        $strSQL = 'SELECT `id` AS `key`, `' . $strTabField . '` AS `value`, `active` ' .
925            'FROM `' . $strTable . '` WHERE `' . $strTabField . "` <> '' AND `" . $strTabField .
926            '` IS NOT NULL ORDER BY `' . $strTabField . '`';
927        return $strSQL;
928    }
929
930    /**
931     * Define SQL commands for command table
932     * @param string $strTabField               Table field
933     * @param string $strDomainWhere1           WHERE SQL domain part
934     * @param string $strAccess                 Access groups
935     * @param int $intOption                    Command type option
936     * @return string                           SQL Statement
937     */
938    private function getRawDataSQLCommand($strTabField, $strDomainWhere1, $strAccess, $intOption)
939    {
940        $strSQL = 'SELECT `id` AS `key`, `' . $strTabField . '` AS `value`, `config_id`, `active` ' .
941            "FROM `tbl_command` WHERE $strDomainWhere1 AND `" . $strTabField . "` <> '' AND `" .
942            $strTabField . "` IS NOT NULL AND `access_group` IN ($strAccess) AND (`command_type` = 0 ".
943            'OR `command_type` = ' . $intOption . ') ORDER BY `' . $strTabField . '`';
944        return $strSQL;
945    }
946
947    /**
948     * Define SQL commands for timeperiod table
949     * @param string $strDomainWhere1           WHERE SQL domain part
950     * @param string $strAccess                 Access groups
951     * @return string                           SQL Statement
952     */
953    private function getRawDataSQLTimeperiod($strDomainWhere1, $strAccess)
954    {
955        $strSQL = 'SELECT `id` AS `key`, `name` AS `value`, `config_id`, `active` ' .
956            "FROM `tbl_timeperiod` WHERE $strDomainWhere1 AND `name` <> '' AND `name` IS NOT NULL ".
957            "AND `access_group` IN ($strAccess) ORDER BY value";
958        return $strSQL;
959    }
960
961    /**
962     * Define SQL commands for service table
963     * @param string $strDomainWhere2           WHERE SQL domain part
964     * @param string $strAccess                 Access groups
965     * @return string                           SQL Statement
966     */
967    private function getRawDataSQLService3($strDomainWhere2, $strAccess)
968    {
969        $strSQLPart1 = "WHERE $strDomainWhere2 AND `tbl_service`.`service_description` <> '' " .
970            'AND `tbl_service`.`service_description` IS NOT NULL AND `tbl_service`.`hostgroup_name` <> 0  ' .
971            "AND `tbl_service`.`access_group` IN ($strAccess) ";
972        $strSQL = "SELECT CONCAT_WS('::',`tbl_host`.`id`,'0',`tbl_service`.`id`) AS `key`, " .
973            "CONCAT('H:',`tbl_host`.`host_name`,',',`tbl_service`.`service_description`) AS `value`, " .
974            '`tbl_service`.`active` FROM `tbl_service` ' .
975            'LEFT JOIN `tbl_lnkServiceToHost` ON `tbl_service`.`id` = `tbl_lnkServiceToHost`.`idMaster` ' .
976            'LEFT JOIN `tbl_host` ON `tbl_lnkServiceToHost`.`idSlave` = `tbl_host`.`id` ' .
977            str_replace('hostgroup_name', 'host_name', $strSQLPart1) .
978            'UNION ' .
979            "SELECT CONCAT_WS('::','0',`tbl_hostgroup`.`id`,`tbl_service`.`id`) AS `key`, " .
980            "CONCAT('HG:',`tbl_hostgroup`.`hostgroup_name`,',',`tbl_service`.`service_description`) " .
981            'AS `value`, `tbl_service`.`active` FROM `tbl_service` ' .
982            'LEFT JOIN `tbl_lnkServiceToHostgroup` ON `tbl_service`.`id`=`tbl_lnkServiceToHostgroup`.`idMaster`' .
983            'LEFT JOIN `tbl_hostgroup` ON `tbl_lnkServiceToHostgroup`.`idSlave` = `tbl_hostgroup`.`id` ' .
984            $strSQLPart1 .
985            'UNION ' .
986            "SELECT CONCAT_WS('::',`tbl_host`.`id`,'0',`tbl_service`.`id`) AS `key`, " .
987            "CONCAT('HHG:',`tbl_host`.`host_name`,',',`tbl_service`.`service_description`) AS `value`, " .
988            '`tbl_service`.`active` FROM `tbl_service` ' .
989            'LEFT JOIN `tbl_lnkServiceToHostgroup` ON `tbl_service`.`id`=`tbl_lnkServiceToHostgroup`.`idMaster`' .
990            'LEFT JOIN `tbl_lnkHostgroupToHost` ON `tbl_lnkHostgroupToHost`.`idMaster` = ' .
991            '`tbl_lnkServiceToHostgroup`.`idSlave` ' .
992            'LEFT JOIN `tbl_host` ON `tbl_lnkHostgroupToHost`.`idSlave` = `tbl_host`.`id` ' .
993            $strSQLPart1 .
994            'UNION ' .
995            "SELECT CONCAT_WS('::',`tbl_host`.`id`,'0',`tbl_service`.`id`) AS `key`, " .
996            "CONCAT('HGH:',`tbl_host`.`host_name`,',',`tbl_service`.`service_description`) AS `value`, " .
997            '`tbl_service`.`active` FROM `tbl_service` ' .
998            'LEFT JOIN `tbl_lnkServiceToHostgroup` ON `tbl_service`.`id`=`tbl_lnkServiceToHostgroup`.`idMaster` ' .
999            'LEFT JOIN `tbl_lnkHostToHostgroup` ON `tbl_lnkHostToHostgroup`.`idSlave` = ' .
1000            '`tbl_lnkServiceToHostgroup`.`idSlave` ' .
1001            'LEFT JOIN `tbl_host` ON `tbl_lnkHostToHostgroup`.`idMaster` = `tbl_host`.`id` ' .
1002            $strSQLPart1 .
1003            'ORDER BY value';
1004        return $strSQL;
1005    }
1006
1007    /**
1008     * Define SQL commands for service table
1009     * @param string $strDomainWhere1           WHERE SQL domain part
1010     * @param string $elem                      Host array
1011     * @param string $strAccess                 Access groups
1012     * @return string                           SQL Statement
1013     */
1014    private function getRawDataSQLService4($strDomainWhere1, $elem, $strAccess)
1015    {
1016        $strSQL = 'SELECT `id`, `service_description` FROM `tbl_service` ' .
1017            'LEFT JOIN `tbl_lnkServiceToHost` ON `tbl_service`.`id` = `tbl_lnkServiceToHost`.`idMaster` ' .
1018            "WHERE $strDomainWhere1 AND `tbl_lnkServiceToHost`.`idSlave` = $elem AND `service_description`<>'' ".
1019            "AND `service_description` IS NOT NULL AND `access_group` IN ($strAccess) " .
1020            'UNION ' .
1021            'SELECT `id`, `service_description` FROM `tbl_service` ' .
1022            'LEFT JOIN `tbl_lnkServiceToHostgroup` ON `tbl_service`.`id`=`tbl_lnkServiceToHostgroup`.`idMaster` ' .
1023            'LEFT JOIN `tbl_lnkHostToHostgroup` ON `tbl_lnkServiceToHostgroup`.`idSlave` = ' .
1024            '`tbl_lnkHostToHostgroup`.`idSlave` ' .
1025            "WHERE $strDomainWhere1 AND `tbl_lnkHostToHostgroup`.`idMaster`=$elem AND `service_description`<>'' ".
1026            " AND `service_description` IS NOT NULL AND `access_group` IN ($strAccess) ".
1027            'UNION ' .
1028            'SELECT `id`, `service_description` FROM `tbl_service` ' .
1029            'LEFT JOIN `tbl_lnkServiceToHostgroup` ON `tbl_service`.`id`=`tbl_lnkServiceToHostgroup`.`idMaster` ' .
1030            'LEFT JOIN `tbl_lnkHostgroupToHost` ON `tbl_lnkServiceToHostgroup`.`idSlave` = ' .
1031            '`tbl_lnkHostgroupToHost`.`idMaster` ' .
1032            "WHERE $strDomainWhere1 AND `tbl_lnkHostgroupToHost`.`idSlave`=$elem AND `service_description`<>'' ".
1033            "AND `service_description` IS NOT NULL AND `access_group` IN ($strAccess)";
1034        return $strSQL;
1035    }
1036
1037    /**
1038     * Define SQL commands for service table
1039     * @param string $strDomainWhere1           WHERE SQL domain part
1040     * @param string $elem                      Hostgroup array
1041     * @param string $strAccess                 Access groups
1042     * @return string                           SQL Statement
1043     */
1044    private function getRawDataSQLService5($strDomainWhere1, $elem, $strAccess)
1045    {
1046        $strSQL = 'SELECT `id`, `service_description` FROM `tbl_service` ' .
1047            'LEFT JOIN `tbl_lnkServiceToHostgroup` ON `tbl_service`.`id`=`tbl_lnkServiceToHostgroup`.`idMaster` ' .
1048            "WHERE $strDomainWhere1 AND `tbl_lnkServiceToHostgroup`.`idSlave` = $elem ".
1049            "AND `service_description` <> '' AND `service_description` IS NOT NULL AND `access_group` ".
1050            "IN ($strAccess)";
1051        return $strSQL;
1052    }
1053
1054    /**
1055     * Define SQL commands for service table
1056     * @param string $strTabField               Table field
1057     * @param string $strWhere                  WHERE SQL domain part
1058     * @param string $strServices               Comma separated list of services
1059     * @param string $strServicesId             Comma separated list of services IDs
1060     * @param string $strAccess                 Access groups
1061     * @return string                           SQL Statement
1062     */
1063    private function getRawDataSQLService6($strTabField, $strWhere, $strServices, $strServicesId, $strAccess)
1064    {
1065        $strSQL = 'SELECT `id` AS `key`, `' . $strTabField . '` AS `value`, `active` FROM `tbl_service` ' .
1066            'LEFT JOIN `tbl_lnkServiceToHost` ON `tbl_service`.`id` = `tbl_lnkServiceToHost`.`idMaster` ' .
1067            "WHERE $strWhere AND `tbl_service`.`service_description` IN ($strServices) ".
1068            "AND `tbl_service`.`id` IN ($strServicesId) AND `" . $strTabField . "` <> '' AND `" .
1069            $strTabField . "` IS NOT NULL AND `access_group` IN ($strAccess) GROUP BY `value` ".
1070            'UNION ' .
1071            'SELECT `id` AS `key`, `' . $strTabField . '` AS `value`, `active` FROM `tbl_service` ' .
1072            'LEFT JOIN `tbl_lnkServiceToHostgroup` ON `tbl_service`.`id`=`tbl_lnkServiceToHostgroup`.`idMaster` ' .
1073            "WHERE $strWhere AND `tbl_service`.`service_description` IN ($strServices) ".
1074            "AND `tbl_service`.`id` IN ($strServicesId) AND `" . $strTabField . "` <> '' AND `" .
1075            $strTabField . "` IS NOT NULL AND `access_group` IN ($strAccess) GROUP BY `value` ".
1076            'UNION ' .
1077            'SELECT `id` AS `key`, `' . $strTabField . '` AS `value`, `active` FROM `tbl_service` ' .
1078            "WHERE $strWhere AND `host_name`=2 OR  `hostgroup_name`=2 AND `" . $strTabField . "` <> '' ".
1079            'AND `' . $strTabField . "` IS NOT NULL AND `access_group` IN ($strAccess) ".
1080            'GROUP BY `value` ORDER BY `value`';
1081        return $strSQL;
1082    }
1083
1084    /**
1085     * Define SQL commands for service table
1086     * @param string $strTabField               Table field
1087     * @param string $strDomainWhere1           WHERE SQL domain part
1088     * @param int $intHostId                    Host ID
1089     * @param string $strAccess                 Access groups
1090     * @return string                           SQL Statement
1091     */
1092    private function getRawDataSQLService7($strTabField, $strDomainWhere1, $intHostId, $strAccess)
1093    {
1094        $strSQL = 'SELECT `tbl_service`.`id` AS `key`, `tbl_service`.`' . $strTabField . '` AS `value`, ' .
1095            '`tbl_service`.`active` FROM `tbl_service` ' .
1096            'LEFT JOIN `tbl_lnkServiceToHost` ON `tbl_service`.`id` = `tbl_lnkServiceToHost`.`idMaster` ' .
1097            "WHERE $strDomainWhere1 AND `tbl_lnkServiceToHost`.`idSlave` = $intHostId AND `" . $strTabField .
1098            "` <> '' AND `" . $strTabField . "` IS NOT NULL AND `access_group` IN ($strAccess) ".
1099            'ORDER BY `' . $strTabField . '`';
1100        return $strSQL;
1101    }
1102
1103    /**
1104     * Define SQL commands for service table
1105     * @param string $strDomainWhere1           WHERE SQL domain part
1106     * @param string $strAccess                 Access groups
1107     * @return string                           SQL Statement
1108     */
1109    private function getRawDataSQLService89($strDomainWhere1, $strAccess)
1110    {
1111        $strSQL = "SELECT `tbl_service`.`id` AS `key`, CONCAT(`tbl_service`.`config_name`, ' - ', ".
1112            '`tbl_service`.`service_description`) AS `value`, `active` ' .
1113            "FROM `tbl_service` WHERE $strDomainWhere1 AND `tbl_service`.`config_name` <> '' ".
1114            "AND `tbl_service`.`config_name` IS NOT NULL AND `tbl_service`.`service_description` <> '' ".
1115            "AND `tbl_service`.`service_description` IS NOT NULL AND `access_group` IN ($strAccess) ".
1116            'ORDER BY `value`';
1117        return $strSQL;
1118    }
1119
1120    /**
1121     * Define SQL commands for service table
1122     * @param string $strDomainWhere2           WHERE SQL domain part for services
1123     * @param string $strAccess                 Access groups
1124     * @return string                           SQL Statement
1125     */
1126    private function getRawDataSQLService10($strDomainWhere2, $strAccess)
1127    {
1128        $strSQL = 'SELECT CONCAT(tbl_service.id, "-", tbl_host.id) AS `key`, CONCAT(tbl_host.host_name, " - ", '
1129            . 'tbl_service.service_description) AS `value`, tbl_service.active '
1130            . 'FROM tbl_service '
1131            . 'LEFT JOIN tbl_lnkServiceToHost ON tbl_service.id=tbl_lnkServiceToHost.idMaster '
1132            . 'LEFT JOIN tbl_host ON tbl_lnkServiceToHost.idSlave=tbl_host.id '
1133            . 'WHERE '.$strDomainWhere2.' AND tbl_service.service_description <> "" '
1134            . 'AND tbl_service.service_description IS NOT NULL AND tbl_host.host_name IS NOT NULL '
1135            . 'AND tbl_service.access_group IN ('.$strAccess.') '
1136            . 'UNION '
1137            . 'SELECT CONCAT(tbl_service.id, "-", tbl_host.id) AS `key`, CONCAT(tbl_host.host_name, " - ", '
1138            . 'tbl_service.service_description) AS `value`, tbl_service.active '
1139            . 'FROM tbl_service '
1140            . 'LEFT JOIN tbl_lnkServiceToHostgroup ON tbl_service.id=tbl_lnkServiceToHostgroup.idMaster '
1141            . 'LEFT JOIN tbl_lnkHostgroupToHost ON tbl_lnkServiceToHostgroup.idSlave = '
1142            . 'tbl_lnkHostgroupToHost.idMaster '
1143            . 'LEFT JOIN tbl_host ON tbl_lnkHostgroupToHost.idSlave=tbl_host.id '
1144            . 'WHERE '.$strDomainWhere2.' AND tbl_service.service_description <> "" '
1145            . 'AND tbl_service.service_description IS NOT NULL AND tbl_host.host_name IS NOT NULL '
1146            . 'AND tbl_service.access_group IN ('.$strAccess.') '
1147            . 'ORDER BY `value`';
1148        return $strSQL;
1149    }
1150
1151    /**
1152     * Define SQL commands for common tables
1153     * @param string $strTable                  Table name
1154     * @param string $strTabField               Table field
1155     * @param string $strDomainWhere1           WHERE SQL domain part
1156     * @param string $strAccess                 Access groups
1157     * @return string                           SQL Statement
1158     */
1159    private function getRawDataSQLCommon($strTable, $strTabField, $strDomainWhere1, $strAccess)
1160    {
1161        $strSQL = 'SELECT `id` AS `key`, `' . $strTabField . '` AS `value`, `config_id`, `active` ' .
1162            'FROM `' . $strTable . "` WHERE $strDomainWhere1 AND `" . $strTabField . "` <> '' ".
1163            'AND `' . $strTabField . "` IS NOT NULL AND `access_group` IN ($strAccess) ".
1164            'ORDER BY `' . $strTabField . '`';
1165        return $strSQL;
1166    }
1167
1168    /**
1169     * Define SQL commands for service table
1170     * @param string $strTabField               Table field
1171     * @param int $intOption                    Option ID
1172     * @param string $strDomainWhere1           WHERE SQL domain part
1173     * @param string $strAccess                 Access groups
1174     * @return string                           SQL Statement
1175     */
1176    private function getRawDataSQLService456($strTabField, $intOption, $strDomainWhere1, $strAccess)
1177    {
1178        // Define variables
1179        if ($intOption == 6) {
1180            $strHostVar      = 'se_host';
1181            $strHostGroupVar = 'se_hostgroup';
1182        } elseif ($intOption == 4) {
1183            $strHostVar      = 'sd_dependent_host';
1184            $strHostGroupVar = 'sd_dependent_hostgroup';
1185        } else {
1186            $strHostVar      = 'sd_host';
1187            $strHostGroupVar = 'sd_hostgroup';
1188        }
1189        if (!isset($this->arrSession['refresh'])) {
1190            $this->arrSession['refresh'] = array();
1191        }
1192        $arrHosts         = array();
1193        $arrHostgroups    = array();
1194        $arrServices      = array();
1195        $arrDataHost      = array();
1196        $arrDataTmp       = array();
1197        $arrHostTemp      = array();
1198        $arrHostgroupTemp = array();
1199        $arrServicesId    = array();
1200        $intDCHost        = 0;
1201        $intDataTmp       = 0;
1202        // Refresh mode - fill arrays
1203        if (isset($this->arrSession['refresh'][$strHostVar]) &&
1204            \is_array($this->arrSession['refresh'][$strHostVar])) {
1205            $arrHosts = $this->arrSession['refresh'][$strHostVar];
1206        } else {
1207            if ($intOption == 4) {
1208                $strSQL = 'SELECT `idSlave` FROM `tbl_lnkServicedependencyToHost_DH` '
1209                    . 'WHERE `idMaster`=' . $this->intDataId;
1210            } elseif ($intOption == 6) {
1211                $strSQL = 'SELECT `idSlave` FROM `tbl_lnkServiceescalationToHost` '
1212                    . 'WHERE `idMaster`=' . $this->intDataId;
1213            } else {
1214                $strSQL = 'SELECT `idSlave` FROM `tbl_lnkServicedependencyToHost_H` '
1215                    . 'WHERE `idMaster`=' .$this->intDataId;
1216            }
1217            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrDataHost, $intDCHost);
1218            if ($booReturn == false) {
1219                $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
1220            } elseif ($intDCHost != 0) {
1221                $arrHostTemp = array();
1222                foreach ($arrDataHost as $elem) {
1223                    $arrHostTemp[] = $elem['idSlave'];
1224                }
1225                $arrHosts = $arrHostTemp;
1226            }
1227        }
1228        if (isset($this->arrSession['refresh'][$strHostGroupVar]) &&
1229            \is_array($this->arrSession['refresh'][$strHostGroupVar])) {
1230            $arrHostgroups = $this->arrSession['refresh'][$strHostGroupVar];
1231        } else {
1232            if ($intOption == 4) {
1233                $strSQL = 'SELECT `idSlave` FROM `tbl_lnkServicedependencyToHostgroup_DH` '
1234                    . 'WHERE `idMaster`=' .$this->intDataId;
1235            } elseif ($intOption == 6) {
1236                $strSQL = 'SELECT `idSlave` FROM `tbl_lnkServiceescalationToHostgroup` '
1237                    . 'WHERE `idMaster`=' . $this->intDataId;
1238            } else {
1239                $strSQL = 'SELECT `idSlave` FROM `tbl_lnkServicedependencyToHostgroup_H` '
1240                    . 'WHERE `idMaster`=' .$this->intDataId;
1241            }
1242            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrDataHost, $intDCHost);
1243            if ($booReturn == false) {
1244                $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
1245            } elseif ($intDCHost != 0) {
1246                $arrHostgroupTemp = array();
1247                foreach ($arrDataHost as $elem) {
1248                    $arrHostgroupTemp[] = $elem['idSlave'];
1249                }
1250                $arrHostgroups = $arrHostgroupTemp;
1251            }
1252        }
1253        if (\is_array($arrHosts) && (\count($arrHosts) == 1) && $arrHosts[0] == '') {
1254            $arrHosts = array();
1255        }
1256        if (\is_array($arrHostgroups) && (\count($arrHostgroups) == 1) && $arrHostgroups[0] == '') {
1257            $arrHostgroups = array();
1258        }
1259        if (\in_array('*', $arrHosts, true)) {
1260            $strSQL = "SELECT id FROM tbl_host WHERE $strDomainWhere1 AND `access_group` IN ($strAccess)";
1261            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrDataHost, $intDCHost);
1262            if ($booReturn == false) {
1263                $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
1264            }
1265            if ($booReturn && ($intDCHost != 0)) {
1266                $arrHostTemp = array();
1267                foreach ($arrDataHost as $elem) {
1268                    if (\in_array('e' . $elem['id'], $this->arrSession['refresh'][$strHostVar], true)) {
1269                        continue;
1270                    }
1271                    $arrHostTemp[] = $elem['id'];
1272                }
1273            }
1274            $strHosts = 1;
1275            $arrHosts = $arrHostTemp;
1276        } else {
1277            $strHosts = \count($arrHosts) + 0;
1278        }
1279        // * Value in host groups -> disabled in NagiosQL 3.2
1280        if (\in_array('*', $arrHostgroups, true)) {
1281            $strSQL = "SELECT id FROM tbl_hostgroup WHERE $strDomainWhere1 AND `access_group` " .
1282                "IN ($strAccess)";
1283            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrDataHost, $intDCHost);
1284            if ($booReturn == false) {
1285                $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
1286            }
1287            if ($booReturn && ($intDCHost != 0)) {
1288                $arrHostgroupTemp = array();
1289                foreach ($arrDataHost as $elem) {
1290                    if (\in_array('e' . $elem['id'], $this->arrSession['refresh'][$strHostGroupVar], true)) {
1291                        continue;
1292                    }
1293                    $arrHostgroupTemp[] = $elem['id'];
1294                }
1295            }
1296            $strHostsGroup = 1;
1297            $arrHostgroups = $arrHostgroupTemp;
1298        } else {
1299            $strHostsGroup = \count($arrHostgroups) + 0;
1300        }
1301        // Special method - only host_name or hostgroup_name selected
1302        if (($strHostVar == 'sd_dependent_host') && ($strHosts == 0) && ($strHostsGroup == 0)) {
1303            if (\is_array($this->arrSession['refresh']['sd_host'])) {
1304                $arrHosts = $this->arrSession['refresh']['sd_host'];
1305            }
1306            if (\is_array($this->arrSession['refresh']['sd_hostgroup'])) {
1307                $arrHostgroups = $this->arrSession['refresh']['sd_hostgroup'];
1308            }
1309            if ((\count($arrHosts) == 1) && $arrHosts[0] == '') {
1310                $arrHosts = array();
1311            }
1312            if ((\count($arrHostgroups) == 1) && $arrHostgroups[0] == '') {
1313                $arrHostgroups = array();
1314            }
1315            $strHosts      = \count($arrHosts) + 0;
1316            $strHostsGroup = \count($arrHostgroups) + 0;
1317        }
1318        // If no hosts and hostgroups are selected show any service
1319        if (($strHosts == 0) && ($strHostsGroup == 0)) {
1320            $strSQL = 'SELECT `id` AS `key`, `' . $strTabField . '` AS `value`, `active` FROM `tbl_service` ' .
1321                "WHERE $strDomainWhere1 AND `" . $strTabField . "` <> '' AND `" . $strTabField . '` ' .
1322                "IS NOT NULL AND `access_group` IN ($strAccess) GROUP BY `value` ORDER BY `value`";
1323        } else {
1324            if ($strHosts != 0) {
1325                $intCounter = 0;
1326                foreach ($arrHosts as $elem) {
1327                    if (($intCounter != 0) && (\count($arrServices) == 0)) {
1328                        continue;
1329                    }
1330                    $arrTempServ = array();
1331                    $arrTempServId = array();
1332                    $elem = str_replace('e', '', $elem);
1333                    $strSQLTmp = $this->getRawDataSQLService4($strDomainWhere1, $elem, $strAccess);
1334                    $booReturn = $this->myDBClass->hasDataArray($strSQLTmp, $arrDataTmp, $intDataTmp);
1335                    if ($booReturn && ($intDataTmp != 0)) {
1336                        foreach ($arrDataTmp as $elem2) {
1337                            if ($intCounter == 0) {
1338                                $arrTempServ[] = $elem2['service_description'];
1339                                $arrTempServId[] = $elem2['id'];
1340                            } elseif (\in_array($elem2['service_description'], $arrServices, true) &&
1341                                !\in_array($elem2['service_description'], $arrTempServ, true)) {
1342                                $arrTempServ[] = $elem2['service_description'];
1343                                $arrTempServId[] = $elem2['id'];
1344                            }
1345                        }
1346                    }
1347                    $arrServices = $arrTempServ;
1348                    $arrServicesId = $arrTempServId;
1349                    $intCounter++;
1350                }
1351            }
1352            if ($strHostsGroup != 0) {
1353                $intCounter = 0;
1354                foreach ($arrHostgroups as $elem) {
1355                    if (($intCounter != 0) && (\count($arrServices) == 0)) {
1356                        continue;
1357                    }
1358                    $arrTempServ = array();
1359                    $arrTempServId = array();
1360                    $elem = str_replace('e', '', $elem);
1361                    $strSQLTmp = $this->getRawDataSQLService5($strDomainWhere1, $elem, $strAccess);
1362                    $booReturn = $this->myDBClass->hasDataArray($strSQLTmp, $arrDataTmp, $intDataTmp);
1363                    if ($booReturn && ($intDataTmp != 0)) {
1364                        foreach ($arrDataTmp as $elem2) {
1365                            if ($intCounter == 0) {
1366                                $arrTempServ[] = $elem2['service_description'];
1367                                $arrTempServId[] = $elem2['id'];
1368                            } elseif (\in_array($elem2['service_description'], $arrServices, true) &&
1369                                !\in_array($elem2['service_description'], $arrTempServ, true)) {
1370                                $arrTempServ[] = $elem2['service_description'];
1371                                $arrTempServId[] = $elem2['id'];
1372                            }
1373                        }
1374                    }
1375                    $arrServices = $arrTempServ;
1376                    $arrServicesId = $arrTempServId;
1377                    $intCounter++;
1378                }
1379            }
1380            if (\count($arrServices) != 0) {
1381                $strServices   = "'" . implode("','", $arrServices) . "'";
1382                $strServicesId = implode(',', $arrServicesId);
1383                $strSQL = $this->getRawDataSQLService6(
1384                    $strTabField,
1385                    $strDomainWhere1,
1386                    $strServices,
1387                    $strServicesId,
1388                    $strAccess
1389                );
1390            } else {
1391                $strSQL = '';
1392            }
1393        }
1394        return $strSQL;
1395    }
1396
1397    /**
1398     * Get selected data
1399     * @param string $strLinkTable              Link table name
1400     * @param array $arrSelect                  Result data array
1401     * @param int $intOption                    Option parameter
1402     * @return int                              0 = successful / 1 = error
1403     */
1404    private function getSelectedItems($strLinkTable, &$arrSelect, $intOption = 0)
1405    {
1406        // Define variables
1407        $arrSelectedRaw = array();
1408        $intDataCount   = 0;
1409        $intReturn      = 1;
1410        // Define SQL commands
1411        if ($intOption == 8) {
1412            $strSQL = 'SELECT * FROM `' .$strLinkTable. '` WHERE `idSlave`=' .$this->intDataId;
1413        } else {
1414            $strSQL = 'SELECT * FROM `' .$strLinkTable. '` WHERE `idMaster`=' .$this->intDataId;
1415        }
1416        // Process data
1417        $booReturn  = $this->myDBClass->hasDataArray($strSQL, $arrSelectedRaw, $intDataCount);
1418        if ($booReturn == false) {
1419            $this->strErrorMessage .= $this->myDBClass->strErrorMessage;
1420        }
1421        if ($booReturn && ($intDataCount != 0)) {
1422            foreach ($arrSelectedRaw as $elem) {
1423                // Multi tables
1424                if ($strLinkTable == 'tbl_lnkServicegroupToService') {
1425                    if (isset($elem['exclude']) && ($elem['exclude'] == 1)) {
1426                        $arrSelect[] = 'e' .$elem['idSlaveH']. '::' .$elem['idSlaveHG']. '::' .$elem['idSlaveS'];
1427                    } else {
1428                        $arrSelect[] = $elem['idSlaveH']. '::' .$elem['idSlaveHG']. '::' .$elem['idSlaveS'];
1429                    }
1430                    // Servicedependencies and -escalations
1431                } elseif (($strLinkTable == 'tbl_lnkServicedependencyToService_DS') ||
1432                    ($strLinkTable == 'tbl_lnkServicedependencyToService_S') ||
1433                    ($strLinkTable == 'tbl_lnkServiceescalationToService')) {
1434                    if (isset($elem['exclude']) && ($elem['exclude'] == 1)) {
1435                        $arrSelect[] = 'e::' .$elem['strSlave'];
1436                    } else {
1437                        $arrSelect[] = $elem['strSlave'];
1438                    }
1439                    // Service parents
1440                } elseif (($strLinkTable == 'tbl_lnkServiceToService') ||
1441                    ($strLinkTable == 'tbl_lnkServicetemplateToService')) {
1442                    $arrSelect[] = $elem['idSlave'].'-'.$elem['idHost'];
1443                    // Standard tables
1444                } else {
1445                    if ($intOption == 8) {
1446                        if (isset($elem['exclude']) && ($elem['exclude'] == 1)) {
1447                            $arrSelect[] = 'e' .$elem['idMaster'];
1448                        } else {
1449                            $arrSelect[] = $elem['idMaster'];
1450                        }
1451                    } else {
1452                        if (isset($elem['exclude']) && ($elem['exclude'] == 1)) {
1453                            $arrSelect[] = 'e' .$elem['idSlave'];
1454                        } else {
1455                            $arrSelect[] = $elem['idSlave'];
1456                        }
1457                    }
1458                }
1459            }
1460            $intReturn = 0;
1461        }
1462        return $intReturn;
1463    }
1464}
1465