1<?php
2///////////////////////////////////////////////////////////////////////////////
3//
4// NagiosQL
5//
6///////////////////////////////////////////////////////////////////////////////
7//
8// (c) 2005-2020 by Martin Willisegger
9//
10// Project   : NagiosQL
11// Component : NagiosQL data processing class
12// Website   : https://sourceforge.net/projects/nagiosql/
13// Website   : https://sourceforge.net/projects/nagiosql/
14// Version   : 3.4.1
15// GIT Repo  : https://gitlab.com/wizonet/NagiosQL
16//
17///////////////////////////////////////////////////////////////////////////////////////////////
18//
19///////////////////////////////////////////////////////////////////////////////////////////////
20//
21// Class: Data processing class
22//
23///////////////////////////////////////////////////////////////////////////////////////////////
24//
25// Includes all functions used to manipulate the configuration data inside the database
26//
27// Name: NagDataClass
28//
29///////////////////////////////////////////////////////////////////////////////////////////////
30namespace functions;
31
32class NagDataClass
33{
34    // Define class variables
35    public $arrSession           = array();  // Session content
36    public $intDomainId          = 0;        // Configuration domain ID
37    public $strUserName          = '';       // Logged in Username
38    public $strErrorMessage      = '';       // String including error messages
39    public $strInfoMessage       = '';       // String including information messages
40
41    // Class includes
42    /** @var MysqliDbClass */
43    public $myDBClass;                       // Database class reference
44    /** @var NagVisualClass */
45    public $myVisClass;                      // NagiosQL visual class object
46    /** @var NagConfigClass */
47    public $myConfigClass;                   // NagiosQL configuration class object
48
49    /**
50     * NagDataClass constructor.
51     * @param array $arrSession                 PHP Session array
52     */
53    public function __construct($arrSession)
54    {
55        if (isset($arrSession['domain'])) {
56            $this->intDomainId = $arrSession['domain'];
57        }
58        if (isset($arrSession['username'])) {
59            $this->strUserName = $arrSession['username'];
60        }
61        $this->arrSession = $arrSession;
62    }
63
64    /**
65     * Saving a given string to the logbook
66     * @param string $strLogMessage             Message string
67     * @return int                              0 = successful / 1 = error
68     */
69    public function writeLog($strLogMessage)
70    {
71        // Variable definition
72        $strRemoteAdress = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
73        $intReturn       = 0;
74        // Write log message to database
75        if ($strRemoteAdress != null) {
76            // Webinterface
77            $strUserName = $this->strUserName;
78            $strDomain   = $this->myDBClass->getFieldData('SELECT `domain` FROM `tbl_datadomain` ' .
79                'WHERE `id`=' .$this->intDomainId);
80            $booReturn   = $this->myDBClass->insertData("INSERT INTO `tbl_logbook` SET `user`='".$strUserName."',".
81                "`time`=NOW(), `ipadress`='".$strRemoteAdress."', `domain`='$strDomain',".
82                "`entry`='".addslashes($strLogMessage)."'");
83            if ($booReturn == false) {
84                $intReturn = 1;
85            }
86        } else {
87            // Scriptinginterface
88            $strUserName   = 'scripting';
89            $strRemoteUser = filter_input(INPUT_SERVER, 'REMOTE_USER', FILTER_SANITIZE_STRING);
90            $strHostname   = filter_input(INPUT_SERVER, 'REMOTE_HOST', FILTER_SANITIZE_STRING);
91            $strSSHClient  = filter_input(INPUT_SERVER, 'SSH_CLIENT', FILTER_SANITIZE_STRING);
92            if ($strRemoteUser != null) {
93                $strUserName .= ' - ' .$strRemoteUser;
94            }
95            $strDomain = $this->myDBClass->getFieldData('SELECT `domain` FROM `tbl_datadomain` ' .
96                'WHERE `id`=' .$this->intDomainId);
97            if ($strHostname != null) {
98                $booReturn = $this->myDBClass->insertData("INSERT INTO `tbl_logbook` SET `user`='".$strUserName."',".
99                    "`time`=NOW(), `ipadress`='".$strHostname."', `domain`='$strDomain', ".
100                    "`entry`='".addslashes($strLogMessage)."'");
101            } elseif ($strSSHClient != null) {
102                $arrSSHClient = explode(' ', $strSSHClient);
103                $booReturn = $this->myDBClass->insertData("INSERT INTO `tbl_logbook` SET `user`='".$strUserName."',".
104                    "`time`=NOW(), `ipadress`='".$arrSSHClient[0]."', `domain`='$strDomain', ".
105                    "`entry`='".addslashes($strLogMessage)."'");
106            } else {
107                $booReturn = $this->myDBClass->insertData("INSERT INTO `tbl_logbook` SET `user`='".$strUserName."',".
108                    "`time`=NOW(), `ipadress`='unknown', `domain`='$strDomain', ".
109                    "`entry`='".addslashes($strLogMessage)."'");
110            }
111            if ($booReturn == false) {
112                $intReturn = 1;
113            }
114        }
115        return $intReturn;
116    }
117
118    /**
119     * Sends an SQL string to the database server
120     * @param string $strSQL                    SQL Command
121     * @param int $intDataID                    Data ID of last inserted dataset (by reference)
122     * @return int                              0 = successful / 1 = error
123     *                                          Status message is stored in message class variables
124     */
125    public function dataInsert($strSQL, &$intDataID)
126    {
127        //Define variables
128        $intReturn = 0;
129        // Send the SQL command to the database server
130        $booReturn = $this->myDBClass->insertData($strSQL);
131        $intDataID = $this->myDBClass->intLastId;
132        // Was the SQL command processed successfully?
133        if ($booReturn) {
134            $this->processClassMessage(translate('Data were successfully inserted to the data base!').
135                '::', $this->strInfoMessage);
136        } else {
137            $this->processClassMessage(translate('Error while inserting the data into the database:').
138                '::' .$this->myDBClass->strErrorMessage. '::', $this->strErrorMessage);
139            $intReturn = 1;
140        }
141        return $intReturn;
142    }
143
144    /**
145     * Merge message strings and check for duplicate messages
146     * @param string $strNewMessage             New message to add
147     * @param string $strOldMessage             Modified message string (by reference)
148     */
149    public function processClassMessage($strNewMessage, &$strOldMessage)
150    {
151        $strNewMessage = str_replace('::::', '::', $strNewMessage);
152        if (($strOldMessage != '') && ($strNewMessage != '')) {
153            if (substr_count($strOldMessage, $strNewMessage) == 0) {
154                $strOldMessage .= $strNewMessage;
155            }
156        } else {
157            $strOldMessage .= $strNewMessage;
158        }
159    }
160
161    /**
162     * Copies one or more records in a data table. Alternatively, an individual record ID
163     * are specified, or the values of the $_POST['chbId_n'] variable is used where n
164     * is the record ID.
165     * @param string $strTableName              Table name
166     * @param string $strKeyField               Key field of the table
167     * @param int $intDataId                    Single data ID to copy
168     * @param int $intDomainId                  Target domain ID
169     * @return int                              0 = successful / 1 = error
170     *                                          Status message is stored in message class variables
171     */
172    public function dataCopyEasy($strTableName, $strKeyField, $intDataId = 0, $intDomainId = -1)
173    {
174        // Define variables
175        $arrRelations = array();
176        $intError     = 0;
177        $intNumber    = 0;
178        $intReturn    = 0;
179        $strAccess    = $this->myVisClass->getAccessGroups('write');
180        if ($intDomainId == -1) {
181            $intDomainId = $this->intDomainId;
182        }
183        // Get all data ID from target table
184        $strAccWhere = "WHERE `access_group` IN ($strAccess)";
185        if (($strTableName == 'tbl_user') || ($strTableName == 'tbl_group')) {
186            $strAccWhere = '';
187        }
188        $strSQL    = 'SELECT `id` FROM `' .$strTableName."` $strAccWhere ORDER BY `id`";
189        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
190        if ($booReturn == false) {
191            $this->processClassMessage(translate('Error while selecting data from database:').
192                '::' .$this->myDBClass->strErrorMessage. '::', $this->strErrorMessage);
193            return 1;
194        }
195        if ($intDataCount != 0) {
196            for ($i=0; $i<$intDataCount; $i++) {
197                // Skip common domain value
198                if ($arrData[$i]['id'] == 0) {
199                    continue;
200                }
201                // Build the name of the form variable
202                $strChbName = 'chbId_' .$arrData[$i]['id'];
203                // If a form variable with this name exists or a matching single data ID was passed
204                if (((filter_input(INPUT_POST, $strChbName, FILTER_SANITIZE_STRING) != null) && ($intDataId == 0)) ||
205                    ($intDataId == $arrData[$i]['id'])) {
206                    // Get all data of this data ID
207                    $strSQL = 'SELECT * FROM `' .$strTableName. '` WHERE `id`=' .$arrData[$i]['id'];
208                    $this->myDBClass->hasSingleDataset($strSQL, $arrData[$i]);
209                    // Build a temporary config name
210                    $strNewName = $this->buildTempConfigName(
211                        $strTableName,
212                        $strKeyField,
213                        $intDomainId,
214                        $intDataCount,
215                        $arrData,
216                        $i
217                    );
218                    // Build the INSERT command based on the table name
219                    $strSQLInsert = $this->buildInsertSQL(
220                        $strTableName,
221                        $strKeyField,
222                        $intDomainId,
223                        $strNewName,
224                        $arrData,
225                        $i
226                    );
227                    // Insert the master dataset
228                    $intCheck    = 0;
229                    $booReturn   = $this->myDBClass->insertData($strSQLInsert);
230                    $intMasterId = $this->myDBClass->intLastId;
231                    if ($booReturn == false) {
232                        $intCheck++;
233                    }
234                    // Copy relations
235                    if (($this->tableRelations($strTableName, $arrRelations) == 0) && ($intCheck == 0)) {
236                        foreach ($arrRelations as $elem) {
237                            // Normal 1:n relation
238                            if ($elem['type'] == '2') {
239                                $intCheck = $this->insertRelationType2($arrData, $i, $elem, $intMasterId, $intCheck);
240                            } elseif ($elem['type'] == '3') { // 1:n relation for templates
241                                $intCheck = $this->insertRelationType3($arrData, $i, $elem, $intMasterId, $intCheck);
242                            } elseif ($elem['type'] == '4') { // Special relation for free variables
243                                $intCheck = $this->insertRelationType4($arrData, $i, $elem, $intMasterId, $intCheck);
244                            } elseif ($elem['type'] == '5') { // 1:n relation for tbl_lnkServicegroupToService
245                                $intCheck = $this->insertRelationType5($arrData, $i, $elem, $intMasterId, $intCheck);
246                            } elseif ($elem['type'] == '6') { // 1:n relation for services
247                                $intCheck = $this->insertRelationType6($arrData, $i, $elem, $intMasterId, $intCheck);
248                            }
249                        }
250                        // 1:n relation for time definitions
251                        if ($strTableName == 'tbl_timeperiod') {
252                            $intCheck = $this->insertRelationTimedefinition($arrData, $i, $intMasterId, $intCheck);
253                        }
254                        // 1:n relation for groups
255                        if ($strTableName == 'tbl_group') {
256                            $intCheck = $this->insertRelationGroup($arrData, $i, $intMasterId, $intCheck);
257                        }
258                        // 1:n relation fot service to host connections
259                        if ($strTableName == 'tbl_host') {
260                            $intCheck = $this->insertRelationHost($arrData, $i, $intMasterId, $intCheck);
261                        }
262                    }
263                    // Write logfile
264                    if ($intCheck != 0) {
265                        // Error
266                        $intError++;
267                        $this->writeLog(translate('Data set copy failed - table [new name]:'). ' ' .$strTableName
268                            . ' [' .$strNewName. ']');
269                        $this->processClassMessage(translate('Data set copy failed - table [new name]:'). ' ' .
270                            $strTableName. ' [' .$strNewName. ']::', $this->strInfoMessage);
271                    } else {
272                        // Success
273                        $this->writeLog(translate('Data set copied - table [new name]:'). ' ' .$strTableName.
274                            ' [' .$strNewName. ']');
275                        $this->processClassMessage(translate('Data set copied - table [new name]:'). ' ' .
276                            $strTableName. ' [' .$strNewName. ']::', $this->strInfoMessage);
277                    }
278                    $intNumber++;
279                }
280            }
281            // Error processing
282            if ($intNumber > 0) {
283                if ($intError == 0) {
284                    // Success
285                    $this->processClassMessage(translate('Data were successfully inserted to the data base!')
286                        . '::', $this->strInfoMessage);
287                    $this->updateStatusTable($strTableName);
288                } else {
289                    // Error
290                    $this->processClassMessage(translate('Error while inserting the data into the database:')
291                        . '::' .$this->myDBClass->strErrorMessage, $this->strInfoMessage);
292                    $intReturn = 1;
293                }
294            } else {
295                $this->processClassMessage(translate('No dataset copied. Maybe the dataset does not exist or you do '.
296                        'not have write permission.'). '::', $this->strErrorMessage);
297                $intReturn = 1;
298            }
299        } else {
300            $this->processClassMessage(translate('No dataset copied. Maybe the dataset does not exist or you do not '.
301                    'have write permission.'). '::', $this->strErrorMessage);
302            $intReturn = 1;
303        }
304        return $intReturn;
305    }
306
307    /**
308     * Returns an array of all datafields of a table, which has an 1:1 or 1:n relation
309     * to another table.
310     * @param string $strTable                  Table name
311     * @param array $arrRelations               Array with relations
312     * @return int                              0 = successful / 1 = error
313     */
314    public function tableRelations($strTable, &$arrRelations)
315    {
316        // Define variable
317        $arrRelations = array();
318        $arrData      = array();
319        $intDC        = 0;
320        $intReturn    = 1;
321        // Get relation data
322        $strSQL    = "SELECT * FROM `tbl_relationinformation` WHERE `master`='$strTable' AND `fullRelation`=0";
323        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
324        if ($booReturn && ($intDC != 0)) {
325            foreach ($arrData as $elem) {
326                $arrRelations[] = array('tableName1' => $elem['tableName1'], 'tableName2' => $elem['tableName2'],
327                    'fieldName'  => $elem['fieldName'],  'linkTable'  => $elem['linkTable'],
328                    'target1'    => $elem['target1'],    'target2'    => $elem['target2'],
329                    'type'       => $elem['type']);
330            }
331            $intReturn = 0;
332        }
333        return $intReturn;
334    }
335
336    /**
337     * Update the date inside the status table (used for last modified date)
338     * @param string $strTable                  Table name
339     * @return int                              0 = successful / 1 = error
340     */
341    public function updateStatusTable($strTable)
342    {
343        // Define variable
344        $arrData      = array();
345        $intDC        = 0;
346        $intReturn    = 1;
347        // Does the entry exist?
348        $strSQL    = "SELECT * FROM `tbl_tablestatus` WHERE `tableName`='$strTable' AND `domainId`=".$this->intDomainId;
349        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
350        if ($booReturn && ($intDC != 0)) {
351            $strSQL    = 'UPDATE `tbl_tablestatus` SET `updateTime`=NOW() ' .
352                "WHERE `tableName`='$strTable' AND `domainId`=".$this->intDomainId;
353            $booReturn = $this->dataInsert($strSQL, $intDataID);
354            if ($booReturn) {
355                $intReturn = 0;
356            }
357        } elseif ($booReturn) {
358            $strSQL    = 'INSERT INTO `tbl_tablestatus` ' .
359                "SET `updateTime`=NOW(), `tableName`='$strTable', `domainId`=".$this->intDomainId;
360            $booReturn = $this->dataInsert($strSQL, $intDataID);
361            if ($booReturn) {
362                $intReturn = 0;
363            }
364        }
365        return $intReturn;
366    }
367
368    /**
369     * Removes one or more dataset(s) from a table. Optinal a single data ID can be passed or the values will be
370     * processed through the POST variable $_POST['chbId_n'] where 'n' represents the data ID.
371     * -> This function does not delete any relation data! <-
372     * @param string $strTableName              Table name
373     * @param int $intDataId                    Single data ID
374     * @return int                              0 = successful / 1 = error
375     *                                          Status message is stored in message class variables
376     */
377    public function dataDeleteEasy($strTableName, $intDataId = 0)
378    {
379        // Define variables
380        $strNoDelete = '';
381        $intReturn   = 0;
382        $arrData     = array();
383        // Special rule for tables with "nodelete" cells
384        if (($strTableName == 'tbl_datadomain') || ($strTableName == 'tbl_configtarget') ||
385            ($strTableName == 'tbl_user')) {
386            $strNoDelete = "AND `nodelete` <> '1'";
387        }
388        // Delete a single data set
389        if ($intDataId != 0) {
390            $strSQL    = 'DELETE FROM `' .$strTableName."` WHERE `id` = $intDataId $strNoDelete";
391            $booReturn = $this->myDBClass->insertData($strSQL);
392            if ($booReturn == false) {
393                $this->processClassMessage(translate('Delete failed because a database error:').
394                    '::' .$this->myDBClass->strErrorMessage. '::', $this->strInfoMessage);
395                $intReturn = 1;
396            } elseif ($this->myDBClass->intAffectedRows == 0) {
397                $this->processClassMessage(translate('No data deleted. The dataset probably does not exist or '.
398                        'is protected from deletion.'). '::', $this->strErrorMessage);
399                $intReturn = 1;
400            } else {
401                $this->strInfoMessage .= translate('Dataset successfully deleted. Affected rows:'). ' ' .
402                    $this->myDBClass->intAffectedRows. '::';
403                $this->writeLog(translate('Delete dataset id:')." $intDataId ".translate('- from table:').
404                    " $strTableName ".translate('- with affected rows:'). ' ' .$this->myDBClass->intAffectedRows);
405                $this->updateStatusTable($strTableName);
406            }
407            // Delete data sets based on form POST parameter
408        } else {
409            $strSQL    = 'SELECT `id` FROM `' .$strTableName. '` WHERE 1=1 ';
410            $strSQL   .= $strNoDelete;
411            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
412            if ($booReturn && ($intDataCount != 0)) {
413                $intDeleteCount = 0;
414                foreach ($arrData as $elem) {
415                    $strChbName = 'chbId_' .$elem['id'];
416                    // Should this data id to be deleted?
417                    if ((filter_input(INPUT_POST, $strChbName) != null) &&
418                        (filter_input(INPUT_POST, $strChbName, FILTER_SANITIZE_STRING) == 'on')) {
419                        $strSQL = 'DELETE FROM `' .$strTableName. '` WHERE `id` = ' .$elem['id'];
420                        $booReturn = $this->myDBClass->insertData($strSQL);
421                        if ($booReturn == false) {
422                            $this->processClassMessage(translate('Delete failed because a database error:').
423                                '::' .$this->myDBClass->strErrorMessage. '::', $this->strInfoMessage);
424                            $intReturn = 1;
425                        } else {
426                            $intDeleteCount += $this->myDBClass->intAffectedRows;
427                        }
428                    }
429                }
430                // Process messsages
431                if ($intDeleteCount == 0) {
432                    $this->processClassMessage(translate('No data deleted. Probably the dataset does not exist or '.
433                            'it is protected from delete.'). '::', $this->strErrorMessage);
434                    $intReturn = 1;
435                } elseif ($intReturn == 0) {
436                    $this->processClassMessage(translate('Dataset successfully deleted. Affected rows:'). ' ' .
437                        $intDeleteCount. '::', $this->strInfoMessage);
438                    $this->writeLog(translate('Deleted data from table:')." $strTableName ".
439                        translate('- with affected rows:'). ' ' .$this->myDBClass->intAffectedRows);
440                    $this->updateStatusTable($strTableName);
441                }
442            } else {
443                $this->processClassMessage(translate('No data deleted. Probably the dataset does not exist or it is '.
444                        'protected from delete.'). '::', $this->strErrorMessage);
445                $intReturn = 1;
446            }
447        }
448        return $intReturn;
449    }
450
451    /**
452     * Removes one or more dataset(s) from a table. Optinal a single data ID can be passed or the values will be
453     * processed through the POST variable $_POST['chbId_n'] where 'n' represents the data ID.
454     * -> This function does also delete relation data! <-
455     * @param string $strTableName              Table name
456     * @param int $intDataId                    Single data ID
457     * @param int $intForce                     Force deletion (1 = force, 1 = no force)
458     * @return int                              0 = successful / 1 = error
459     *                                          Status message is stored in message class variables
460     */
461    public function dataDeleteFull($strTableName, $intDataId = 0, $intForce = 0)
462    {
463        // Define variables
464        $arrRelations = array();
465        $arrData      = array();
466        $arrConfigId  = array();
467        // Get write access groups
468        $strAccess = $this->myVisClass->getAccessGroups('write');
469        // Get all relations
470        $this->fullTableRelations($strTableName, $arrRelations);
471        // Get all datasets
472        if ($strTableName == 'tbl_group') {
473            $strSQL = 'SELECT `id` FROM `' .$strTableName. '`';
474        } else {
475            $strSQL = 'SELECT `id` FROM `' .$strTableName. '` ' .
476                'WHERE `config_id`=' .$this->intDomainId." AND `access_group` IN ($strAccess)";
477        }
478        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
479        if ($booReturn && ($intDataCount != 0)) {
480            $intDeleteCount  = 0;
481            $strInfoMessage  = '';
482            $strErrorMessage = '';
483
484            foreach ($arrData as $elem) {
485                $strChbName = 'chbId_' .$elem['id'];
486                // Single ID
487                if (($intDataId != 0) && ($intDataId != $elem['id'])) {
488                    continue;
489                }
490                // Should this data id to be deleted?
491                if ((($intDataId == $elem['id']) || ((filter_input(INPUT_POST, $strChbName) != null) &&
492                            (filter_input(INPUT_POST, $strChbName, FILTER_SANITIZE_STRING) == 'on'))) &&
493                    (($this->infoRelation($strTableName, $elem['id'], 'id', 1) == 0) || ($intForce == 1))) {
494                    // Delete relations
495                    if (!\is_array($arrRelations)) {
496                        $arrRelations = array();
497                    }
498                    foreach ($arrRelations as $rel) {
499                        $strSQL = '';
500                        // Process flags
501                        $arrFlags = explode(',', $rel['flags']);
502                        // Simple 1:n relation
503                        if ($arrFlags[3] == 1) {
504                            $strSQL = 'DELETE FROM `' .$rel['tableName1']. '` ' .
505                                'WHERE `' .$rel['fieldName']. '`=' .$elem['id'];
506                        }
507                        // Simple 1:1 relation
508                        if ($arrFlags[3] == 0) {
509                            // Delete relation
510                            if ($arrFlags[2] == 0) {
511                                $strSQL = 'DELETE FROM `' .$rel['tableName1']. '` ' .
512                                    'WHERE `' .$rel['fieldName']. '`=' .$elem['id'];
513                                // Set slave to 0
514                            } elseif ($arrFlags[2] == 2) {
515                                $strSQL = 'UPDATE `' .$rel['tableName1']. '` SET `' .$rel['fieldName']. '`=0 ' .
516                                    'WHERE `' .$rel['fieldName']. '`=' .$elem['id'];
517                            }
518                        }
519                        // Special 1:n relation for variables
520                        if ($arrFlags[3] == 2) {
521                            $strSQL    = 'SELECT * FROM `' .$rel['tableName1']. '` WHERE `idMaster`=' .$elem['id'];
522                            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
523                            if ($booReturn && ($intDataCount != 0)) {
524                                foreach ($arrData as $vardata) {
525                                    $strSQL = 'DELETE FROM `tbl_variabledefinition` ' .
526                                        'WHERE `id`=' .$vardata['idSlave'];
527                                    $this->myDBClass->insertData($strSQL);
528                                }
529                            }
530                            $strSQL = 'DELETE FROM `' .$rel['tableName1']. '` WHERE `idMaster`=' .$elem['id'];
531                        }
532                        // Special 1:n relation for time definitions
533                        if ($arrFlags[3] == 3) {
534                            $strSQL = 'DELETE FROM `tbl_timedefinition` WHERE `tipId`=' .$elem['id'];
535                            $this->myDBClass->insertData($strSQL);
536                        }
537                        if ($strSQL != '') {
538                            $this->myDBClass->insertData($strSQL);
539                        }
540                    }
541                    // Delete host configuration file
542                    if (($strTableName == 'tbl_host') && ($this->intDomainId != 0)) {
543                        $strSQL    = 'SELECT `host_name` FROM `tbl_host` WHERE `id`=' .$elem['id'];
544                        $strHost   = $this->myDBClass->getFieldData($strSQL);
545                        $this->myConfigClass->getConfigSets($arrConfigId);
546                        if ($arrConfigId != 1) {
547                            $intReturn = 0;
548                            foreach ($arrConfigId as $intConfigId) {
549                                $intReturn += $this->myConfigClass->moveFile(
550                                    'host',
551                                    $strHost. '.cfg',
552                                    $intConfigId
553                                );
554                            }
555                            if ($intReturn == 0) {
556                                $this->processClassMessage(translate('The assigned, no longer used configuration '.
557                                        'files were deleted successfully!'). '::', $strInfoMessage);
558                                $this->writeLog(translate('Host file deleted:'). ' ' .$strHost. '.cfg');
559                            } else {
560                                $strErrorMessage .= translate('Errors while deleting the old configuration file - '.
561                                        'please check!:'). ' ::' .$this->myConfigClass->strErrorMessage . '::';
562                            }
563                        }
564                    }
565                    // Delete service configuration file
566                    if (($strTableName == 'tbl_service') && ($this->intDomainId != 0)) {
567                        $strSQL     = 'SELECT `config_name` FROM `tbl_service` WHERE `id`=' .$elem['id'];
568                        $strService = $this->myDBClass->getFieldData($strSQL);
569                        $strSQL     = "SELECT * FROM `tbl_service` WHERE `config_name` = '$strService'";
570                        $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
571                        if ($intDataCount == 1) {
572                            $this->myConfigClass->getConfigSets($arrConfigId);
573                            if ($arrConfigId != 1) {
574                                $intReturn = 0;
575                                foreach ($arrConfigId as $intConfigId) {
576                                    $intReturn += $this->myConfigClass->moveFile(
577                                        'service',
578                                        $strService. '.cfg',
579                                        $intConfigId
580                                    );
581                                }
582                                if ($intReturn == 0) {
583                                    $this->processClassMessage(translate('The assigned, no longer used '.
584                                            'configuration files were deleted successfully!').
585                                        '::', $strInfoMessage);
586                                    $this->writeLog(translate('Host file deleted:'). ' ' .$strService. '.cfg');
587                                } else {
588                                    $strErrorMessage .=  translate('Errors while deleting the old configuration '.
589                                            'file - please check!:'). '::' .
590                                        $this->myConfigClass->strErrorMessage. '::';
591                                }
592                            }
593                        }
594                    }
595                    // Delete main entry
596                    $strSQL = 'DELETE FROM `' .$strTableName. '` WHERE `id`=' .$elem['id'];
597                    $this->myDBClass->insertData($strSQL);
598                    $intDeleteCount++;
599                }
600            }
601            // Process messages
602            if ($intDeleteCount == 0) {
603                $this->processClassMessage(translate('No data deleted. Probably the dataset does not exist, it is '.
604                        'protected from deletion, you do not have write permission or it has relations to other '.
605                        'configurations which cannot be deleted. Use the "info" function for detailed informations '.
606                        'about relations!'). '::', $this->strErrorMessage);
607                return 1;
608            }
609
610            $this->updateStatusTable($strTableName);
611            $this->processClassMessage(translate('Dataset successfully deleted. Affected rows:'). ' ' .
612                $intDeleteCount. '::', $this->strInfoMessage);
613            $this->writeLog(translate('Deleted data from table:')." $strTableName ".
614                translate('- with affected rows:'). ' ' .$intDeleteCount);
615            $this->processClassMessage($strInfoMessage, $this->strInfoMessage);
616            $this->processClassMessage($strErrorMessage, $this->strErrorMessage);
617            return 0;
618        }
619        $this->processClassMessage(translate('No data deleted. Probably the dataset does not exist, it is '.
620                'protected from deletion or you do not have write permission.'). '::' .
621            $this->myDBClass->strErrorMessage, $this->strErrorMessage);
622        return 1;
623    }
624
625    /**
626     * Returns an array with any data fields from a table with existing relations to another table. This function
627     * returns also passive relations which are not used in configurations.
628     * This function is used for a full deletion of a configuration entry or to find out if a configuration is used
629     * in another way.
630     * @param string $strTable                  Table name
631     * @param array $arrRelations               Array with relations
632     * @return int                              0 = no field with relation / 1 = at least one field with relation
633     *                                          Status message is stored in message class variables
634     * Data array:      tableName               Table include the relation data
635     *                  fieldName               Field name include the relation data
636     *                  flags                   Pos 1 -> 0=Normal field / 1=Required field      (field type)
637     *                                          Pos 2 -> 0=delete / 1=keep data / 2=set to 0    (normal deletion option)
638     *                                          Pos 3 -> 0=delete / 2=set to 0                  (force deletion option)
639     *                                          Pos 4 -> 0=1:1 / 1=1:n /                        (relation type)
640     *                                                   2=1:n (variables) / 3=1:n              (timedef)
641     */
642    public function fullTableRelations($strTable, &$arrRelations)
643    {
644        // Define variable
645        $arrRelations = array();
646        $arrData      = array();
647        $intDC        = 0;
648        $intReturn    = 0;
649        // Get relation data
650        $strSQL    = "SELECT * FROM `tbl_relationinformation` WHERE `master`='$strTable' AND `fullRelation`=1";
651        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
652        if ($booReturn && ($intDC != 0)) {
653            foreach ($arrData as $elem) {
654                $arrRelations[] = array('tableName1' => $elem['tableName1'], 'fieldName' => $elem['fieldName'],
655                    'target1'    => $elem['target1'],    'targetKey' => $elem['targetKey'],
656                    'flags'      => $elem['flags']);
657            }
658            $intReturn = 1;
659        }
660        return $intReturn;
661    }
662
663    /**
664     * Searches any relation in the database and returns them as relation information
665     * @param string $strTable                  Database table name
666     * @param int $intMasterId                  Data ID from master table
667     * @param string $strMasterfield            Info field name from master table
668     * @param int $intReporting                 Output as text - 0=yes, 1=no
669     * @return int                              0 = successful / 1 = error
670     *                                          Status message is stored in message class variables
671     */
672    public function infoRelation($strTable, $intMasterId, $strMasterfield, $intReporting = 0)
673    {
674        $intDeletion  = 0;
675        $arrDSCount   = array();
676        $arrRelations = array();
677        $arrData      = array();
678        $arrDataCheck = array();
679        $intReturn    = $this->fullTableRelations($strTable, $arrRelations);
680        if ($intReturn == 1) {
681            // Get master field data
682            $strNewMasterfield = str_replace(',', '`,`', $strMasterfield);
683            $strSQL            = 'SELECT `' .$strNewMasterfield. '` FROM `' .$strTable."` WHERE `id` = $intMasterId";
684            $this->myDBClass->hasSingleDataset($strSQL, $arrSource);
685            if (substr_count($strMasterfield, ',') != 0) {
686                $arrTarget = explode(',', $strMasterfield);
687                $strName   = $arrSource[$arrTarget[0]]. '-' .$arrSource[$arrTarget[1]];
688            } else {
689                $strName   = $arrSource[$strMasterfield];
690            }
691            $this->strInfoMessage .= '<span class="blackmessage">' .translate('Relation information for <b>').
692                $strName.translate('</b> of table <b>').$strTable. ':</b></span>::';
693            $this->strInfoMessage .= '<span class="bluemessage">';
694            // Walk through relations
695            foreach ($arrRelations as $elem) {
696                // Process flags
697                $arrFlags = explode(',', $elem['flags']);
698                if ($elem['fieldName'] == 'check_command') {
699                    $strSQL = 'SELECT * FROM `' .$elem['tableName1']. '` ' .
700                        'WHERE SUBSTRING_INDEX(`' .$elem['fieldName']."`,'!',1)= $intMasterId";
701                } else {
702                    $strSQL = 'SELECT * FROM `' .$elem['tableName1']. '` WHERE `' .$elem['fieldName']."`= $intMasterId";
703                }
704                $booReturn  = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
705                // Take only used relations
706                if ($booReturn && ($intDataCount != 0)) {
707                    // Relation type
708                    if ($arrFlags[3] == 1) {
709                        foreach ($arrData as $data) {
710                            if ($elem['fieldName'] == 'idMaster') {
711                                $strRef = 'idSlave';
712                                // Process special tables
713                                if ($elem['target1'] == 'tbl_service') {
714                                    if ($elem['tableName1'] == 'tbl_lnkServicegroupToService') {
715                                        $strRef = 'idSlaveS';
716                                    }
717                                } elseif ($elem['target1'] == 'tbl_host') {
718                                    if ($elem['tableName1'] == 'tbl_lnkServicegroupToService') {
719                                        $strRef = 'idSlaveH';
720                                    }
721                                } elseif ($elem['target1'] == 'tbl_hostgroup') {
722                                    if ($elem['tableName1'] == 'tbl_lnkServicegroupToService') {
723                                        $strRef = 'idSlaveHG';
724                                    }
725                                }
726                            } else {
727                                $strRef = 'idMaster';
728                            }
729                            // Get data
730                            $strSQL = 'SELECT * FROM `' .$elem['tableName1']. '` ' .
731                                'LEFT JOIN `' .$elem['target1']. '` ON `' .$strRef. '` = `id` ' .
732                                'WHERE `' .$elem['fieldName']. '` = ' .$data[$elem['fieldName']]. ' ' .
733                                'AND `' .$strRef. '`=' .$data[$strRef];
734                            $this->myDBClass->hasSingleDataset($strSQL, $arrDSTarget);
735                            if (substr_count($elem['targetKey'], ',') != 0) {
736                                $arrTarget = explode(',', $elem['targetKey']);
737                                $strTarget = $arrDSTarget[$arrTarget[0]]. '-' .$arrDSTarget[$arrTarget[1]];
738                            } else {
739                                $strTarget = $arrDSTarget[$elem['targetKey']];
740                            }
741                            // If the field is market as "required", check for any other entries
742                            if ($arrFlags[0] == 1) {
743                                $strSQL = 'SELECT * FROM `' .$elem['tableName1']. '` ' .
744                                    'WHERE `' .$strRef. '` = ' .$arrDSTarget[$strRef];
745                                $booReturn  = $this->myDBClass->hasDataArray($strSQL, $arrDSCount, $intDCCount);
746                                if ($booReturn && ($intDCCount > 1)) {
747                                    $this->strInfoMessage .= translate('Relation to <b>').$elem['target1'].
748                                        translate('</b>, entry <b>').$strTarget.
749                                        '</b> - <span style="color:#00CC00;">' .translate('deletion <b>possible</b>').
750                                        '</span>::';
751                                } else {
752                                    $this->strInfoMessage .= translate('Relation to <b>').$elem['target1'].
753                                        translate('</b>, entry <b>').$strTarget.
754                                        '</b> - <span style="color:#FF0000;">' .
755                                        translate('deletion <b>not possible</b>'). '</span>::';
756                                    $intDeletion = 1;
757                                }
758                            } else {
759                                $this->strInfoMessage .= translate('Relation to <b>').$elem['target1'].
760                                    translate('</b>, entry <b>').$strTarget. '</b> - <span style="color:#00CC00;">' .
761                                    translate('deletion <b>possible</b>'). '</span>::';
762                            }
763                        }
764                    } elseif ($arrFlags[3] == 0) {
765                        // Fetch remote entry
766                        $strSQL = 'SELECT * FROM `' .$elem['tableName1']. '` '
767                            . 'WHERE `' .$elem['fieldName']."`=$intMasterId";
768                        $booReturn  = $this->myDBClass->hasDataArray($strSQL, $arrDataCheck, $intDCCheck);
769                        if ($booReturn && ($intDCCheck != 0)) {
770                            foreach ($arrDataCheck as $data) {
771                                if (substr_count($elem['targetKey'], ',') != 0) {
772                                    $arrTarget = explode(',', $elem['targetKey']);
773                                    $strTarget = $data[$arrTarget[0]]. '-' .$data[$arrTarget[1]];
774                                } else {
775                                    $strTarget = $data[$elem['targetKey']];
776                                }
777                                if ($arrFlags[0] == 1) {
778                                    $this->strInfoMessage .= translate('Relation to <b>').$elem['tableName1'].
779                                        translate('</b>, entry <b>').$strTarget.
780                                        '</b> - <span style="color:#FF0000;">' .
781                                        translate('deletion <b>not possible</b>'). '</span>::';
782                                    $intDeletion = 1;
783                                } else {
784                                    $this->strInfoMessage .= translate('Relation to <b>').$elem['tableName1'].
785                                        translate('</b>, entry <b>').$strTarget.
786                                        '</b> - <span style="color:#00CC00;">' .
787                                        translate('deletion <b>possible</b>'). '</span>::';
788                                }
789                            }
790                        }
791                    }
792                }
793            }
794            $this->strInfoMessage .= '</span>::';
795        }
796        if ($intReporting == 1) {
797            $this->strInfoMessage = '';
798        }
799        return $intDeletion;
800    }
801
802    /**
803     * Inserts any necessary dataset for an 1:n (optional 1:n:n) relation to the database table
804     * @param string $strTable                  Database table name
805     * @param int $intMasterId                  Data ID from master table
806     * @param array $arrSlaveId                 Array with all data IDs from slave table
807     * @param int $intMulti                     0 = for 1:n relations
808     *                                          1 = for 1:n:n relations
809     * @return int                              0 = successful / 1 = error
810     */
811    public function dataInsertRelation($strTable, $intMasterId, $arrSlaveId, $intMulti = 0)
812    {
813        // Define variables
814        $intReturn = 0;
815        $intDataId = 0;
816        $strSQL    = '';
817        // Walk through the slave data ID array
818        foreach ($arrSlaveId as $elem) {
819            // Pass empty and '*' values
820            if ($elem == '0') {
821                continue;
822            }
823            if ($elem == '*') {
824                continue;
825            }
826            // Process exclude values
827            if (0 === strpos($elem, 'e')) {
828                $elem       = str_replace('e', '', $elem);
829                $intExclude = 1;
830            } else {
831                $intExclude = 0;
832            }
833            // Define the SQL statement
834            if ($intMulti != 0) {
835                $arrValues = explode('::', $elem);
836                $strSQL    = 'INSERT INTO `' .$strTable."` SET `idMaster`=$intMasterId, `idSlaveH`=".$arrValues[0]
837                    . ', `idSlaveHG`=' .$arrValues[1]. ', `idSlaveS`=' .$arrValues[2].",  `exclude`=$intExclude";
838            } else {
839                if (($strTable == 'tbl_lnkServicedependencyToService_DS') ||
840                    ($strTable == 'tbl_lnkServicedependencyToService_S')  ||
841                    ($strTable == 'tbl_lnkServiceescalationToService')) {
842                    // Get service description
843                    $strSQLSrv  = "SELECT `service_description` FROM `tbl_service` WHERE id=$elem";
844                    $strService = $this->myDBClass->getFieldData($strSQLSrv);
845                    $strSQL     = 'INSERT INTO `' .$strTable."` SET `idMaster`=$intMasterId, `idSlave`=$elem, ".
846                        "`strSlave`='".addslashes($strService)."', `exclude`=$intExclude";
847                } elseif (($strTable == 'tbl_lnkServiceToService') ||
848                    ($strTable == 'tbl_lnkServicetemplateToService')) {
849                    $arrValues = explode('-', $elem);
850                    if (isset($arrValues[0]) && isset($arrValues[1])) {
851                        $strSQL = 'INSERT INTO `' .$strTable."` SET `idMaster`=$intMasterId, `idSlave`=$arrValues[0], "
852                            ." `idHost`=$arrValues[1]";
853                    }
854                } elseif (($strTable != 'tbl_lnkTimeperiodToTimeperiod') &&
855                    ($strTable != 'tbl_lnkDatadomainToConfigtarget')) {
856                    $strSQL = 'INSERT INTO `' . $strTable . '` ' .
857                        "SET `idMaster`=$intMasterId, `idSlave`=$elem, `exclude`=$intExclude";
858                } else {
859                    $strSQL = 'INSERT INTO `' .$strTable."` SET `idMaster`=$intMasterId, `idSlave`=$elem";
860                }
861            }
862            // Insert data
863            $intReturn = $this->dataInsert($strSQL, $intDataId);
864            if ($intReturn != 0) {
865                $intReturn = 1;
866            }
867        }
868        return $intReturn;
869    }
870
871    /**
872     * Update the datasets for 1:n (optional 1:n:m) relations in the database table
873     * @param string $strTable                  Database table name
874     * @param int $intMasterId                  Data ID from master table
875     * @param array $arrSlaveId                 Array with all data IDs from slave table
876     * @param int $intMulti                     0 = for 1:n relations
877     *                                          1 = for 1:n:n relations
878     * @return int                              0 = successful / 1 = error
879     */
880    public function dataUpdateRelation($strTable, $intMasterId, $arrSlaveId, $intMulti = 0)
881    {
882        $intReturn = 0;
883        // Remove any old relations
884        $intReturn1 = $this->dataDeleteRelation($strTable, $intMasterId);
885        if ($intReturn1 != 0) {
886            $intReturn = 1;
887        }
888        // Insert the new relations
889        if ($intReturn == 0) {
890            $intReturn2 = $this->dataInsertRelation($strTable, $intMasterId, $arrSlaveId, $intMulti);
891            if ($intReturn2 != 0) {
892                $intReturn = 1;
893            }
894        }
895        return $intReturn;
896    }
897
898    /**
899     * Removes any relation from the database
900     * @param string $strTable                  Database table name
901     * @param int $intMasterId                  Data ID from master table
902     * @return int                              0 = successful / 1 = error
903     */
904    public function dataDeleteRelation($strTable, $intMasterId)
905    {
906        // Define variables
907        $intDataId = 0;
908        // Define the SQL statement
909        $strSQL    = 'DELETE FROM `' .$strTable."` WHERE `idMaster`=$intMasterId";
910        return $this->dataInsert($strSQL, $intDataId);
911    }
912
913    /**
914     * Deactivates one or many datasets in the table be setting 'active' to '0'. Alternatively, a single record
915     * ID can be specified or evaluated by the values of $_POST['chbId_n'] passed parameters, where n is the
916     * record ID must match.
917     * @param string $strTableName              Table name
918     * @param int $intDataId                    Individual record ID, which is to be activate
919     * @return int                              0 = successful / 1 = error
920     *                                          Status message is stored in message class variables
921     */
922    public function dataDeactivate($strTableName, $intDataId = 0)
923    {
924        // Define variables
925        $intReturn = 1;
926        $arrData   = array();
927        // Get write access groups
928        $strAccess = $this->myVisClass->getAccessGroups('write');
929        // Activate datasets
930        $strSQL    = 'SELECT `id` FROM `' .$strTableName. '` ' .
931            'WHERE `config_id`=' .$this->intDomainId." AND `access_group` IN ($strAccess)";
932        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
933        if ($booReturn && ($intDataCount != 0)) {
934            $intActivateCount = 0;
935            foreach ($arrData as $elem) {
936                $strChbName = 'chbId_' .$elem['id'];
937                // was the current record is marked for activate?
938                if ((($intDataId == $elem['id']) || ((filter_input(INPUT_POST, $strChbName) != null) &&
939                            (filter_input(INPUT_POST, $strChbName, FILTER_SANITIZE_STRING) == 'on'))) &&
940                    $this->infoRelation($strTableName, $elem['id'], 'id', 1) == 0) {
941                    // Update dataset
942                    if (($strTableName == 'tbl_service') || ($strTableName == 'tbl_host')) {
943                        $strSQL = 'UPDATE `' .$strTableName."` SET `active`='0', `last_modified`=now() ".
944                            'WHERE `id`=' .$elem['id'];
945                    } else {
946                        $strSQL = 'UPDATE `' .$strTableName."` SET `active`='0' WHERE `id`=".$elem['id'];
947                    }
948                    $this->myDBClass->insertData($strSQL);
949                    $intActivateCount++;
950                }
951            }
952            // Process informations
953            if ($intActivateCount == 0) {
954                $this->processClassMessage(translate('No dataset deactivated. Maybe the dataset does not exist, it '.
955                        'is protected from deactivation, no dataset was selected or you do not have write permission. '.
956                        'Use the "info" function for detailed informations about relations!').
957                    '::', $this->strErrorMessage);
958            } else {
959                $this->updateStatusTable($strTableName);
960                $this->processClassMessage(translate('Dataset successfully deactivated. Affected rows:'). ' ' .
961                    $intActivateCount. '::', $this->strInfoMessage);
962                $this->writeLog(translate('Deactivate dataset from table:')." $strTableName ".
963                    translate('- with affected rows:'). ' ' .$this->myDBClass->intAffectedRows);
964                $intReturn = 0;
965            }
966        } else {
967            $this->processClassMessage(translate('No dataset deactivated. Maybe the dataset does not exist or you '.
968                    'do not have write permission.'). '::', $this->strErrorMessage);
969        }
970        return $intReturn;
971    }
972
973    /**
974     * Activates one or many datasets in the table be setting 'active' to '1'. Alternatively, a single record ID can
975     * be specified or evaluated by the values of $_POST['chbId_n'] passed parameters, where n is the record ID must
976     * match.
977     * @param string $strTableName              Table name
978     * @param int $intDataId                    Individual record ID, which is to be activate
979     * @return int                              0 = successful / 1 = error
980     *                                          Status message is stored in message class variables
981     */
982    public function dataActivate($strTableName, $intDataId = 0)
983    {
984        // Define variables
985        $intReturn = 1;
986        $arrData   = array();
987        // Get write access groups
988        $strAccess = $this->myVisClass->getAccessGroups('write');
989        // Activate datasets
990        $strSQL    = 'SELECT `id` FROM `' .$strTableName. '` ' .
991            'WHERE `config_id`=' .$this->intDomainId." AND `access_group` IN ($strAccess)";
992        $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDataCount);
993        if ($booReturn && ($intDataCount != 0)) {
994            $intActivateCount = 0;
995            foreach ($arrData as $elem) {
996                $strChbName = 'chbId_' .$elem['id'];
997                // was the current record is marked for activate?
998                if (($intDataId == $elem['id']) || ((filter_input(INPUT_POST, $strChbName) != null) &&
999                        (filter_input(INPUT_POST, $strChbName, FILTER_SANITIZE_STRING) == 'on'))) {
1000                    // Update dataset
1001                    if (($strTableName == 'tbl_service') || ($strTableName == 'tbl_host')) {
1002                        $strSQL = 'UPDATE `' .$strTableName."` SET `active`='1', `last_modified`=now() ".
1003                            'WHERE `id`=' .$elem['id'];
1004                    } else {
1005                        $strSQL = 'UPDATE `' .$strTableName."` SET `active`='1' WHERE `id`=".$elem['id'];
1006                    }
1007                    $this->myDBClass->insertData($strSQL);
1008                    $intActivateCount++;
1009                }
1010            }
1011            // Process informations
1012            if ($intActivateCount == 0) {
1013                $this->processClassMessage(translate('No dataset activated. Maybe the dataset does not exist, no '.
1014                        'dataset was selected or you do not have write permission.'). '::', $this->strErrorMessage);
1015            } else {
1016                $this->updateStatusTable($strTableName);
1017                $this->processClassMessage(translate('Dataset successfully activated. Affected rows:'). ' ' .
1018                    $intActivateCount. '::', $this->strInfoMessage);
1019                $this->writeLog(translate('Activate dataset from table:')." $strTableName ".
1020                    translate('- with affected rows:'). ' ' .$this->myDBClass->intAffectedRows);
1021                $intReturn = 0;
1022            }
1023        } else {
1024            $this->processClassMessage(translate('No dataset activated. Maybe the dataset does not exist or you do '.
1025                    'not have write permission.'). '::', $this->strErrorMessage);
1026        }
1027        return $intReturn;
1028    }
1029
1030    /**
1031     * Updates the hash field im some configuration objects
1032     * @param string $strTable                  Table name
1033     * @param int $intId                        Data ID
1034     * @return int                              0 = successful / 1 = error
1035     *                                          Status message is stored in message class variables
1036     */
1037    public function updateHash($strTable, $intId)
1038    {
1039        // Define variables
1040        $strRawString = '';
1041        $arrData      = array();
1042        $intDC        = 0;
1043        $intDataID    = 0;
1044        // Service table
1045        if ($strTable == 'tbl_service') {
1046            // Get any hosts and host_groups
1047            $strSQL  = 'SELECT `host_name` AS `item_name` FROM `tbl_host` ' .
1048                "LEFT JOIN `tbl_lnkServiceToHost` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1049                'UNION SELECT `hostgroup_name` AS `item_name` FROM `tbl_hostgroup` ' .
1050                'LEFT JOIN `tbl_lnkServiceToHostgroup` ON `idSlave`=`id` ' .
1051                'WHERE `idMaster`=' .$intId. ' ORDER BY `item_name`';
1052            $booRet  = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
1053            if ($booRet && ($intDC != 0)) {
1054                foreach ($arrData as $elem) {
1055                    $strRawString .= $elem['item_name']. ',';
1056                }
1057            }
1058            $strSQL = 'SELECT * FROM `tbl_service` WHERE `id`=' .$intId;
1059            $booRet = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
1060            if ($booRet && ($intDC != 0)) {
1061                if ($arrData[0]['service_description'] != '') {
1062                    $strRawString .= $arrData[0]['service_description']. ',';
1063                }
1064                if ($arrData[0]['display_name'] != '') {
1065                    $strRawString .= $arrData[0]['display_name']. ',';
1066                }
1067                if ($arrData[0]['check_command'] != '') {
1068                    $arrField      = explode('!', $arrData[0]['check_command']);
1069                    $strCommand    = strstr($arrData[0]['check_command'], '!');
1070                    $strSQLRel     = 'SELECT `command_name` FROM `tbl_command` WHERE `id`=' .$arrField[0];
1071                    $strName       = $this->myDBClass->getFieldData($strSQLRel);
1072                    $strRawString .= $strName.$strCommand. ',';
1073                }
1074            }
1075        }
1076        if (($strTable == 'tbl_hostdependency') || ($strTable == 'tbl_servicedependency')) {
1077            // Get * values
1078            $strSQL = 'SELECT * FROM `' .$strTable. '` WHERE `id`=' .$intId;
1079            $booRet  = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
1080            if ($booRet && ($intDC != 0)) {
1081                if (isset($arrData[0]['dependent_host_name'])  && ($arrData[0]['dependent_host_name'] == 2)) {
1082                    $strRawString .= 'any,';
1083                }
1084                if (isset($arrData[0]['dependent_hostgroup_name']) && ($arrData[0]['dependent_hostgroup_name'] == 2)) {
1085                    $strRawString .= 'any,';
1086                }
1087                if (isset($arrData[0]['host_name']) && ($arrData[0]['host_name'] == 2)) {
1088                    $strRawString .= 'any,';
1089                }
1090                if (isset($arrData[0]['hostgroup_name']) && ($arrData[0]['hostgroup_name'] == 2)) {
1091                    $strRawString .= 'any,';
1092                }
1093                if (isset($arrData[0]['dependent_service_description']) &&
1094                    ($arrData[0]['dependent_service_description'] == 2)) {
1095                    $strRawString .= 'any,';
1096                }
1097                if (isset($arrData[0]['service_description']) && ($arrData[0]['service_description'] == 2)) {
1098                    $strRawString .= 'any,';
1099                }
1100            }
1101            if ($strTable == 'tbl_hostdependency') {
1102                // Get any hosts and host_groups
1103                $strSQL  = 'SELECT `host_name` AS `item_name`, exclude FROM `tbl_host` ' .
1104                    "LEFT JOIN `tbl_lnkHostdependencyToHost_DH` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1105                    'UNION ALL SELECT `hostgroup_name` AS `item_name`, exclude FROM `tbl_hostgroup` ' .
1106                    "LEFT JOIN `tbl_lnkHostdependencyToHostgroup_DH` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1107                    'UNION ALL SELECT `host_name` AS `item_name`, exclude FROM `tbl_host` ' .
1108                    "LEFT JOIN `tbl_lnkHostdependencyToHost_H` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1109                    'UNION ALL SELECT `hostgroup_name` AS `item_name`, exclude FROM `tbl_hostgroup` ' .
1110                    'LEFT JOIN `tbl_lnkHostdependencyToHostgroup_H` ON `idSlave`=`id` WHERE `idMaster`=' .$intId;
1111            }
1112            if ($strTable == 'tbl_servicedependency') {
1113                // Get any hosts and host_groups
1114                $strSQL  = 'SELECT `host_name` AS `item_name`, exclude FROM `tbl_host` ' .
1115                    "LEFT JOIN `tbl_lnkServicedependencyToHost_DH` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1116                    'UNION ALL SELECT `hostgroup_name` AS `item_name`, exclude FROM `tbl_hostgroup` ' .
1117                    'LEFT JOIN `tbl_lnkServicedependencyToHostgroup_DH` ON `idSlave`=`id` ' .
1118                    "WHERE `idMaster`=$intId ".
1119                    'UNION ALL SELECT `host_name` AS `item_name`, exclude FROM `tbl_host` ' .
1120                    "LEFT JOIN `tbl_lnkServicedependencyToHost_H` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1121                    'UNION ALL SELECT `hostgroup_name` AS `item_name`, exclude FROM `tbl_hostgroup` ' .
1122                    'LEFT JOIN `tbl_lnkServicedependencyToHostgroup_H` ON `idSlave`=`id` ' .
1123                    "WHERE `idMaster`=$intId ".
1124                    'UNION ALL SELECT `strSlave` AS `item_name`, exclude ' .
1125                    "FROM `tbl_lnkServicedependencyToService_DS` WHERE `idMaster`=$intId ".
1126                    'UNION ALL SELECT `strSlave` AS `item_name`, exclude ' .
1127                    "FROM `tbl_lnkServicedependencyToService_S` WHERE `idMaster`=$intId";
1128            }
1129            $booRet  = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
1130            if ($booRet && ($intDC != 0)) {
1131                foreach ($arrData as $elem) {
1132                    if ($elem['exclude'] == 0) {
1133                        $strRawString .= $elem['item_name']. ',';
1134                    } else {
1135                        $strRawString .= 'not_' .$elem['item_name']. ',';
1136                    }
1137                }
1138                $strRawString = substr($strRawString, 0, -1);
1139            }
1140        }
1141        if (($strTable == 'tbl_hostescalation') || ($strTable == 'tbl_serviceescalation')) {
1142            // Get * values
1143            $strSQL = 'SELECT * FROM `' .$strTable. '` WHERE `id`=' .$intId;
1144            $booRet  = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
1145            if ($booRet && ($intDC != 0)) {
1146                if (isset($arrData[0]['host_name']) && ($arrData[0]['host_name'] == 2)) {
1147                    $strRawString .= 'any,';
1148                }
1149                if (isset($arrData[0]['hostgroup_name']) && ($arrData[0]['hostgroup_name'] == 2)) {
1150                    $strRawString .= 'any,';
1151                }
1152                if (isset($arrData[0]['contacts']) && ($arrData[0]['contacts'] == 2)) {
1153                    $strRawString .= 'any,';
1154                }
1155                if (isset($arrData[0]['contact_groups']) && ($arrData[0]['contact_groups'] == 2)) {
1156                    $strRawString .= 'any,';
1157                }
1158                if (isset($arrData[0]['service_description']) && ($arrData[0]['service_description'] == 2)) {
1159                    $strRawString .= 'any,';
1160                }
1161            }
1162            // Get any hosts, host_groups, contacts and contact_groups
1163            if ($strTable == 'tbl_hostescalation') {
1164                $strSQL  = 'SELECT `host_name` AS `item_name`, exclude FROM `tbl_host` ' .
1165                    "LEFT JOIN `tbl_lnkHostescalationToHost` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1166                    'UNION ALL SELECT `hostgroup_name` AS `item_name`, exclude  FROM `tbl_hostgroup` ' .
1167                    "LEFT JOIN `tbl_lnkHostescalationToHostgroup` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1168                    'UNION ALL SELECT `contact_name` AS `item_name`, exclude  FROM `tbl_contact` ' .
1169                    "LEFT JOIN `tbl_lnkHostescalationToContact` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1170                    'UNION ALL SELECT `contactgroup_name` AS `item_name`, exclude  FROM `tbl_contactgroup` ' .
1171                    "LEFT JOIN `tbl_lnkHostescalationToContactgroup` ON `idSlave`=`id` WHERE `idMaster`=$intId";
1172            }
1173            if ($strTable == 'tbl_serviceescalation') {
1174                $strSQL  = 'SELECT `host_name` AS `item_name`, exclude FROM `tbl_host` ' .
1175                    "LEFT JOIN `tbl_lnkServiceescalationToHost` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1176                    'UNION ALL SELECT `hostgroup_name` AS `item_name`, exclude  FROM `tbl_hostgroup` ' .
1177                    "LEFT JOIN `tbl_lnkServiceescalationToHostgroup` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1178                    'UNION ALL SELECT `contact_name` AS `item_name`, exclude  FROM `tbl_contact` ' .
1179                    "LEFT JOIN `tbl_lnkServiceescalationToContact` ON `idSlave`=`id` WHERE `idMaster`=$intId ".
1180                    'UNION ALL SELECT `contactgroup_name` AS `item_name`, exclude  FROM `tbl_contactgroup` ' .
1181                    'LEFT JOIN `tbl_lnkServiceescalationToContactgroup` ON `idSlave`=`id` ' .
1182                    "WHERE `idMaster`=$intId ".
1183                    'UNION ALL SELECT `strSlave` AS `item_name`, exclude ' .
1184                    "FROM `tbl_lnkServiceescalationToService` WHERE `idMaster`=$intId";
1185            }
1186            $booRet  = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
1187            if ($booRet && ($intDC != 0)) {
1188                foreach ($arrData as $elem) {
1189                    if ($elem['exclude'] == 0) {
1190                        $strRawString .= $elem['item_name']. ',';
1191                    } else {
1192                        $strRawString .= 'not_' .$elem['item_name']. ',';
1193                    }
1194                }
1195                $strRawString = substr($strRawString, 0, -1);
1196            }
1197        }
1198        if ($strTable == 'tbl_serviceextinfo') {
1199            // Get any hosts and host_groups
1200            $strSQL  = 'SELECT `tbl_host`.`host_name` AS `item_name` FROM `tbl_host` ' .
1201                'LEFT JOIN `tbl_serviceextinfo` ON `tbl_host`.`id`=`tbl_serviceextinfo`.`host_name` ' .
1202                "WHERE `tbl_serviceextinfo`.`id`=$intId ".
1203                'UNION SELECT `tbl_service`.`service_description` AS `item_name` FROM `tbl_service` ' .
1204                'LEFT JOIN `tbl_serviceextinfo` ON ' .
1205                '`tbl_service`.`id`=`tbl_serviceextinfo`.`service_description` ' .
1206                "WHERE `tbl_serviceextinfo`.`id`=$intId ORDER BY `item_name`";
1207            $booRet  = $this->myDBClass->hasDataArray($strSQL, $arrData, $intDC);
1208            if ($booRet && ($intDC != 0)) {
1209                foreach ($arrData as $elem) {
1210                    $strRawString .= $elem['item_name']. ',';
1211                }
1212                $strRawString = substr($strRawString, 0, -1);
1213            }
1214        }
1215        // Remove blanks
1216        while (substr_count($strRawString, ' ') != 0) {
1217            $strRawString = str_replace(' ', '', $strRawString);
1218        }
1219        // Sort hash string
1220        $arrTemp = explode(',', $strRawString);
1221        sort($arrTemp);
1222        $strRawString = implode(',', $arrTemp);
1223        // Update has in database
1224        $strSQL    = 'UPDATE `' .$strTable."` SET `import_hash`='".sha1($strRawString)."' WHERE `id`='$intId'";
1225        //echo "Hash: ".$strRawString." --> ".sha1($strRawString)."<br>";
1226        return $this->dataInsert($strSQL, $intDataID);
1227    }
1228
1229    /**
1230     * PRIVATE functions
1231     */
1232
1233    /**
1234     * Manually set some NULL values based on field names (key)
1235     * @param string $strTableName              Table name
1236     * @param string $key                       Data key (field name)
1237     * @param string $value                     Data value (field key)
1238     * @return NULL|string                      Manipulated data value
1239     */
1240    private function setNullValues($strTableName, $key, $value)
1241    {
1242        $arrNull = array('normal_check_interval', 'retry_check_interval', 'max_check_attempts', 'low_flap_threshold',
1243            'high_flap_threshold', 'freshness_threshold', 'notification_interval', 'first_notification_delay',
1244            'check_interval', 'retry_interval');
1245        if (\in_array($key, $arrNull, true) && ($value == '')) {
1246            $value = 'NULL';
1247        }
1248        // manually set some NULL values based on table name
1249        if (($strTableName == 'tbl_serviceextinfo') && ($key == 'service_description')) {
1250            $value = '0';
1251        }
1252        // Do not copy the password in tbl_user
1253        if (($strTableName == 'tbl_user') && ($key == 'password')) {
1254            $value = 'xxxxxxx';
1255        }
1256        // Do not copy nodelete and webserver authentification values in tbl_user
1257        if ($key == 'nodelete') {
1258            $value = '0';
1259        }
1260        if ($key == 'wsauth') {
1261            $value = '0';
1262        }
1263        return $value;
1264    }
1265
1266    /**
1267     * Insert a normal 1:n relation
1268     * @param array $arrData                    Database value array
1269     * @param integer $intID                    Database array key
1270     * @param array $elem                       Link table information
1271     * @param integer $intMasterId              Data ID of master table
1272     * @param integer $intCheck                 Check error counter (before processing)
1273     * @return integer                          Check error counter (after processing)
1274     */
1275    private function insertRelationType2($arrData, $intID, $elem, $intMasterId, $intCheck)
1276    {
1277        $arrRelData      = array();
1278        $intRelDataCount = 0;
1279        if ($arrData[$intID][$elem['fieldName']] != 0) {
1280            $strSQL = 'SELECT `idSlave`, `exclude` FROM `' .$elem['linkTable']. '` ' .
1281                'WHERE `idMaster`=' .$arrData[$intID]['id'];
1282            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrRelData, $intRelDataCount);
1283            if ($booReturn && ($intRelDataCount != 0)) {
1284                foreach ($arrRelData as $elem2) {
1285                    $strSQLRel = 'INSERT INTO `' . $elem['linkTable'] . '` ' .
1286                        "SET `idMaster`=$intMasterId, `idSlave`=" . $elem2['idSlave'] . ', ' .
1287                        '`exclude`=' . $elem2['exclude'];
1288                    $booReturn = $this->myDBClass->insertData($strSQLRel);
1289                    if ($booReturn == false) {
1290                        $intCheck++;
1291                    }
1292                }
1293            }
1294        }
1295        return $intCheck;
1296    }
1297
1298    /**
1299     * Insert a 1:n relation for templates
1300     * @param array $arrData                    Database value array
1301     * @param integer $intID                    Database array key
1302     * @param array $elem                       Link table information
1303     * @param integer $intMasterId              Data ID of master table
1304     * @param integer $intCheck                 Check error counter (before processing)
1305     * @return integer                          Check error counter (after processing)
1306     */
1307    private function insertRelationType3($arrData, $intID, $elem, $intMasterId, $intCheck)
1308    {
1309        $arrRelData      = array();
1310        $intRelDataCount = 0;
1311        if ($arrData[$intID][$elem['fieldName']] == 1) {
1312            $strSQL = 'SELECT `idSlave`,`idSort`,`idTable` FROM `' . $elem['linkTable'] . '` ' .
1313                'WHERE `idMaster`=' . $arrData[$intID]['id'];
1314            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrRelData, $intRelDataCount);
1315            if ($booReturn && ($intRelDataCount != 0)) {
1316                foreach ($arrRelData as $elem2) {
1317                    $strSQLRel = 'INSERT INTO `' . $elem['linkTable'] . '` ' .
1318                        "SET `idMaster`=$intMasterId, `idSlave`=" . $elem2['idSlave'] . ', ' .
1319                        '`idTable`=' . $elem2['idTable'] . ', `idSort`=' . $elem2['idSort'];
1320                    $booReturn = $this->myDBClass->insertData($strSQLRel);
1321                    if ($booReturn == false) {
1322                        $intCheck++;
1323                    }
1324                }
1325            }
1326        }
1327        return $intCheck;
1328    }
1329
1330    /**
1331     * Insert a special relation for free variables
1332     * @param array $arrData                    Database value array
1333     * @param integer $intID                    Database array key
1334     * @param array $elem                       Link table information
1335     * @param integer $intMasterId              Data ID of master table
1336     * @param integer $intCheck                 Check error counter (before processing)
1337     * @return integer                          Check error counter (after processing)
1338     */
1339    private function insertRelationType4($arrData, $intID, $elem, $intMasterId, $intCheck)
1340    {
1341        $arrRelData      = array();
1342        $arrDataVar      = array();
1343        $intRelDataCount = 0;
1344        $intDCVar        = 0;
1345        if ($arrData[$intID][$elem['fieldName']] != 0) {
1346            $strSQL = 'SELECT `idSlave` FROM `' . $elem['linkTable'] . '` ' .
1347                'WHERE `idMaster` = ' . $arrData[$intID]['id'];
1348            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrRelData, $intRelDataCount);
1349            if ($booReturn && ($intRelDataCount != 0)) {
1350                foreach ($arrRelData as $elem2) {
1351                    // Copy variables and link them to the new master
1352                    $strSQLVar = 'SELECT * FROM `tbl_variabledefinition` WHERE `id`=' . $elem2['idSlave'];
1353                    $booReturn = $this->myDBClass->hasDataArray($strSQLVar, $arrDataVar, $intDCVar);
1354                    if ($booReturn && ($intDCVar != 0)) {
1355                        $strSQLInsVar = 'INSERT INTO `tbl_variabledefinition` ' .
1356                            "SET `name`='" . addslashes($arrDataVar[0]['name']) . "', " .
1357                            "`value`='" . addslashes($arrDataVar[0]['value']) . "', " .
1358                            '`last_modified`=NOW()';
1359                        $booReturn = $this->myDBClass->insertData($strSQLInsVar);
1360                        if ($booReturn == false) {
1361                            $intCheck++;
1362                        }
1363                        $strSQLRel = 'INSERT INTO `' . $elem['linkTable'] . '` ' .
1364                            "SET `idMaster`=$intMasterId, " .
1365                            '`idSlave`=' . $this->myDBClass->intLastId;
1366                        $booReturn = $this->myDBClass->insertData($strSQLRel);
1367                        if ($booReturn == false) {
1368                            $intCheck++;
1369                        }
1370                    }
1371                }
1372            }
1373        }
1374        return $intCheck;
1375    }
1376
1377    /**
1378     * Insert a 1:n relation for tbl_lnkServicegroupToService
1379     * @param array $arrData                    Database value array
1380     * @param integer $intID                    Database array key
1381     * @param array $elem                       Link table information
1382     * @param integer $intMasterId              Data ID of master table
1383     * @param integer $intCheck                 Check error counter (before processing)
1384     * @return integer                          Check error counter (after processing)
1385     */
1386    private function insertRelationType5($arrData, $intID, $elem, $intMasterId, $intCheck)
1387    {
1388        $arrRelData      = array();
1389        $intRelDataCount = 0;
1390        if ($arrData[$intID][$elem['fieldName']] != 0) {
1391            $strSQL = 'SELECT `idSlaveH`,`idSlaveHG`,`idSlaveS`,`exclude` ' .
1392                'FROM `' . $elem['linkTable'] . '` WHERE `idMaster`=' . $arrData[$intID]['id'];
1393            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrRelData, $intRelDataCount);
1394            if ($booReturn && ($intRelDataCount != 0)) {
1395                foreach ($arrRelData as $elem2) {
1396                    $strSQLRel = 'INSERT INTO `' . $elem['linkTable'] . '` ' .
1397                        "SET `idMaster`=$intMasterId, `idSlaveH`=" . $elem2['idSlaveH'] . ', ' .
1398                        '`idSlaveHG`=' . $elem2['idSlaveHG'] . ', `idSlaveS`=' . $elem2['idSlaveS'] . ', `exclude`=' .
1399                        $elem2['exclude'];
1400                    $booReturn = $this->myDBClass->insertData($strSQLRel);
1401                    if ($booReturn == false) {
1402                        $intCheck++;
1403                    }
1404                }
1405            }
1406        }
1407        return $intCheck;
1408    }
1409
1410    /**
1411     * Insert a 1:n relation for services
1412     * @param array $arrData                    Database value array
1413     * @param integer $intID                    Database array key
1414     * @param array $elem                       Link table information
1415     * @param integer $intMasterId              Data ID of master table
1416     * @param integer $intCheck                 Check error counter (before processing)
1417     * @return integer                          Check error counter (after processing)
1418     */
1419    private function insertRelationType6($arrData, $intID, $elem, $intMasterId, $intCheck)
1420    {
1421        $arrRelData      = array();
1422        $intRelDataCount = 0;
1423        if ($arrData[$intID][$elem['fieldName']] != 0) {
1424            $strSQL = 'SELECT `idSlave`, `strSlave`, `exclude` ' .
1425                'FROM `' . $elem['linkTable'] . '` WHERE `idMaster`=' . $arrData[$intID]['id'];
1426            $booReturn = $this->myDBClass->hasDataArray($strSQL, $arrRelData, $intRelDataCount);
1427            if ($booReturn && ($intRelDataCount != 0)) {
1428                foreach ($arrRelData as $elem2) {
1429                    $strSQLRel = 'INSERT INTO `' . $elem['linkTable'] . '` ' .
1430                        "SET `idMaster`=$intMasterId, `idSlave`=" . $elem2['idSlave'] . ', ' .
1431                        "`strSlave`='" . addslashes($elem2['strSlave']) . "', " .
1432                        '`exclude`=' . $elem2['exclude'];
1433                    $booReturn = $this->myDBClass->insertData($strSQLRel);
1434                    if ($booReturn == false) {
1435                        $intCheck++;
1436                    }
1437                }
1438            }
1439        }
1440        return $intCheck;
1441    }
1442
1443    /**
1444     * Insert a 1:n relation for time definitions
1445     * @param array $arrData                    Database value array
1446     * @param integer $intID                    Database array key
1447     * @param integer $intMasterId              Data ID of master table
1448     * @param integer $intCheck                 Check error counter (before processing)
1449     * @return integer                          Check error counter (after processing)
1450     */
1451    private function insertRelationTimedefinition($arrData, $intID, $intMasterId, $intCheck)
1452    {
1453        $arrRelDataTP = array();
1454        $intRelDataCountTP = 0;
1455        $strSQL = 'SELECT * FROM `tbl_timedefinition` WHERE `tipId`=' . $arrData[$intID]['id'];
1456        $this->myDBClass->hasDataArray($strSQL, $arrRelDataTP, $intRelDataCountTP);
1457        if ($intRelDataCountTP != 0) {
1458            foreach ($arrRelDataTP as $elem) {
1459                $strSQLRel = 'INSERT INTO `tbl_timedefinition` (`tipId`,`definition`,`range`,' .
1460                    "`last_modified`) VALUES ($intMasterId,'" . addslashes($elem['definition']) . "'," .
1461                    "'" . addslashes($elem['range']) . "',now())";
1462                $booReturn = $this->myDBClass->insertData($strSQLRel);
1463                if ($booReturn == false) {
1464                    $intCheck++;
1465                }
1466            }
1467        }
1468        return $intCheck;
1469    }
1470
1471    /**
1472     * Insert a 1:n relation for user groups
1473     * @param array $arrData                    Database value array
1474     * @param integer $intID                    Database array key
1475     * @param integer $intMasterId              Data ID of master table
1476     * @param integer $intCheck                 Check error counter (before processing)
1477     * @return integer                          Check error counter (after processing)
1478     */
1479    private function insertRelationGroup($arrData, $intID, $intMasterId, $intCheck)
1480    {
1481        $arrRelDataTP = array();
1482        $intRelDataCountTP = 0;
1483        $strSQL = 'SELECT * FROM `tbl_lnkGroupToUser` WHERE `idMaster`=' . $arrData[$intID]['id'];
1484        $this->myDBClass->hasDataArray($strSQL, $arrRelDataTP, $intRelDataCountTP);
1485        if ($intRelDataCountTP != 0) {
1486            foreach ($arrRelDataTP as $elem2) {
1487                $strSQLRel = 'INSERT INTO `tbl_lnkGroupToUser` (`idMaster`,`idSlave`,`read`,`write`,`link`) ' .
1488                    "VALUES ($intMasterId,'" . $elem2['idSlave'] . "','" . $elem2['read'] . "',".
1489                    "'" . $elem2['write'] . "','" . $elem2['link'] . "')";
1490                $booReturn = $this->myDBClass->insertData($strSQLRel);
1491                if ($booReturn == false) {
1492                    $intCheck++;
1493                }
1494            }
1495        }
1496        return $intCheck;
1497    }
1498
1499    /**
1500     * Insert a 1:n relation fot service to host connections
1501     * @param array $arrData                    Database value array
1502     * @param integer $intID                    Database array key
1503     * @param integer $intMasterId              Data ID of master table
1504     * @param integer $intCheck                 Check error counter (before processing)
1505     * @return integer                          Check error counter (after processing)
1506     */
1507    private function insertRelationHost($arrData, $intID, $intMasterId, $intCheck)
1508    {
1509        $arrRelDataSH = array();
1510        $intRelDataCountSH = 0;
1511        $strSQL = 'SELECT * FROM `tbl_lnkServiceToHost` WHERE `idSlave`=' . $arrData[$intID]['id'];
1512        $this->myDBClass->hasDataArray($strSQL, $arrRelDataSH, $intRelDataCountSH);
1513        if ($intRelDataCountSH != 0) {
1514            foreach ($arrRelDataSH as $elem2) {
1515                $strSQLRel = 'INSERT INTO `tbl_lnkServiceToHost` (`idMaster`,`idSlave`,`exclude`) ' .
1516                    "VALUES ('" . $elem2['idMaster'] . "',$intMasterId,'" . $elem2['exclude'] . "')";
1517                $booReturn = $this->myDBClass->insertData($strSQLRel);
1518                if ($booReturn == false) {
1519                    $intCheck++;
1520                }
1521            }
1522        }
1523        return $intCheck;
1524    }
1525
1526    /**
1527     * Build an INSERT command based on the table name
1528     * @param string $strTableName              Table name
1529     * @param string $strKeyField               Configuration field name
1530     * @param int $intDomainId                  Domain ID
1531     * @param string $strNewName                New configuration name
1532     * @param array $arrData                    Data array
1533     * @param int $intID                        Data array key
1534     * @return string                           SQL INSERT command
1535     */
1536    private function buildInsertSQL($strTableName, $strKeyField, $intDomainId, $strNewName, $arrData, $intID)
1537    {
1538        $strSQLInsert = 'INSERT INTO `' . $strTableName . '` SET `' . $strKeyField . "`='" . $strNewName . "'";
1539        /** @noinspection ForeachSourceInspection */
1540        foreach ($arrData[$intID] as $key => $value) {
1541            if (($key != $strKeyField) && ($key != 'active') && ($key != 'last_modified') &&
1542                ($key != 'id') && ($key != 'config_id')) {
1543                // manually set some NULL values based on field names
1544                $value = $this->setNullValues($strTableName, $key, $value);
1545                // If the data value is not "NULL", add single quotes to the value
1546                if ($value != 'NULL') {
1547                    $strSQLInsert .= ',`' . $key . "`='" . addslashes($value) . "'";
1548                } else {
1549                    $strSQLInsert .= ',`' . $key . '`=' . $value;
1550                }
1551            }
1552        }
1553        if (($strTableName == 'tbl_user') || ($strTableName == 'tbl_group') ||
1554            ($strTableName == 'tbl_datadomain') || ($strTableName == 'tbl_configtarget')) {
1555            $strSQLInsert .= ",`active`='0', `last_modified`=NOW()";
1556        } else {
1557            $strSQLInsert .= ",`active`='0', `config_id`=$intDomainId, `last_modified`=NOW()";
1558        }
1559        return $strSQLInsert;
1560    }
1561
1562    /**
1563     * Build a temporary configuration name
1564     * @param string $strTableName              Table name
1565     * @param string $strKeyField               Configuration field name
1566     * @param int $intDomainId                  Domain ID
1567     * @param int $intCount                     Dataset counter
1568     * @param array $arrData                    Data array
1569     * @param int $intID                        Data array key
1570     * @return string                           Temporary configuration name
1571     */
1572    private function buildTempConfigName($strTableName, $strKeyField, $intDomainId, $intCount, $arrData, $intID)
1573    {
1574        // Define variables
1575        $strNewName = '';
1576        for ($y = 1; $y <= $intCount; $y++) {
1577            $strNewName = $arrData[$intID][$strKeyField] . " ($y)";
1578            if (($strTableName == 'tbl_user') || ($strTableName == 'tbl_group') ||
1579                ($strTableName == 'tbl_datadomain') || ($strTableName == 'tbl_configtarget')) {
1580                $strSQL = 'SELECT `id` FROM `' . $strTableName . '` WHERE `' . $strKeyField . "`='$strNewName'";
1581                $booReturn = $this->myDBClass->getFieldData($strSQL);
1582            } else {
1583                $strSQL = 'SELECT `id` FROM `' . $strTableName . '` ' .
1584                    'WHERE `' . $strKeyField . "`='$strNewName' AND `config_id`=$intDomainId";
1585                $booReturn = $this->myDBClass->getFieldData($strSQL);
1586            }
1587            // If the name is unused -> break the loop
1588            if ($booReturn == false) {
1589                break;
1590            }
1591        }
1592        // Manually overwrite new name for extinfo tables
1593        if ($strTableName == 'tbl_hostextinfo') {
1594            $strNewName = '0';
1595        }
1596        if ($strTableName == 'tbl_serviceextinfo') {
1597            $strNewName = '0';
1598        }
1599        return $strNewName;
1600    }
1601}
1602