コード例 #1
0
ファイル: scripts.inc.php プロジェクト: rennhak/zabbix
function get_script_by_scriptid($scriptid)
{
    $sql = 'SELECT * FROM scripts WHERE scriptid=' . $scriptid;
    $rows = false;
    if ($res = DBSelect($sql)) {
        $rows = DBfetch($res);
    }
    return $rows;
}
コード例 #2
0
function GetMun($GeoCod)
{
    $Reg = array();
    $Link = DBServerConnect();
    if ($Link !== FALSE) {
        DBSelect(cDBName);
        $SQL = "SELECT * FROM Municipios WHERE Geocodigo = {$GeoCod} LIMIT 1;";
        $ExeSQL = mysql_query($SQL);
        //  or die (mysql_error());;
        $Total = MySQLResults($ExeSQL);
        if ($Total > 0) {
            $Reg = mysql_fetch_array($ExeSQL);
        }
        DBServerDisconnect($Link);
    }
    return $Reg;
}
コード例 #3
0
    // get items
    $data['hostPrototypes'] = API::HostPrototype()->get(array('discoveryids' => $data['parent_discoveryid'], 'output' => API_OUTPUT_EXTEND, 'selectTemplates' => array('templateid', 'name'), 'editable' => true, 'sortfield' => $sortField, 'limit' => $config['search_limit'] + 1));
    order_result($data['hostPrototypes'], $sortField, $sortOrder);
    $data['paging'] = getPagingLine($data['hostPrototypes'], $sortOrder);
    // fetch templates linked to the prototypes
    $templateIds = array();
    foreach ($data['hostPrototypes'] as $hostPrototype) {
        $templateIds = array_merge($templateIds, zbx_objectValues($hostPrototype['templates'], 'templateid'));
    }
    $templateIds = array_unique($templateIds);
    $linkedTemplates = API::Template()->get(array('output' => array('templateid', 'name'), 'templateids' => $templateIds, 'selectParentTemplates' => array('hostid', 'name')));
    $data['linkedTemplates'] = zbx_toHash($linkedTemplates, 'templateid');
    // fetch source templates and LLD rules
    $hostPrototypeSourceIds = getHostPrototypeSourceParentIds(zbx_objectValues($data['hostPrototypes'], 'hostid'));
    if ($hostPrototypeSourceIds) {
        $hostPrototypeSourceTemplates = DBfetchArrayAssoc(DBSelect('SELECT h.hostid,h2.name,h2.hostid AS parent_hostid' . ' FROM hosts h,host_discovery hd,items i,hosts h2' . ' WHERE h.hostid=hd.hostid' . ' AND hd.parent_itemid=i.itemid' . ' AND i.hostid=h2.hostid' . ' AND ' . dbConditionInt('h.hostid', $hostPrototypeSourceIds)), 'hostid');
        foreach ($data['hostPrototypes'] as &$hostPrototype) {
            if ($hostPrototype['templateid']) {
                $sourceTemplate = $hostPrototypeSourceTemplates[$hostPrototypeSourceIds[$hostPrototype['hostid']]];
                $hostPrototype['sourceTemplate'] = array('hostid' => $sourceTemplate['parent_hostid'], 'name' => $sourceTemplate['name']);
                $sourceDiscoveryRuleId = get_realrule_by_itemid_and_hostid($discoveryRule['itemid'], $sourceTemplate['hostid']);
                $hostPrototype['sourceDiscoveryRuleId'] = $sourceDiscoveryRuleId;
            }
        }
        unset($hostPrototype);
    }
    // render view
    $itemView = new CView('configuration.host.prototype.list', $data);
    $itemView->render();
    $itemView->show();
}
コード例 #4
0
ファイル: blocks.inc.php プロジェクト: phedders/zabbix
function make_webmon_overview()
{
    global $USER_DETAILS;
    $available_hosts = get_accessible_hosts_by_user($USER_DETAILS, PERM_READ_ONLY, PERM_RES_IDS_ARRAY);
    $table = new CTableInfo();
    $table->setHeader(array(is_show_all_nodes() ? S_NODE : null, S_HOST_GROUP, S_OK, S_FAILED, S_IN_PROGRESS, S_UNKNOWN));
    $sql = 'SELECT DISTINCT g.groupid, g.name ' . ' FROM httptest ht, applications a, groups g, hosts_groups hg ' . ' WHERE ' . DBcondition('hg.hostid', $available_hosts) . ' AND hg.hostid=a.hostid ' . ' AND g.groupid=hg.groupid ' . ' AND a.applicationid=ht.applicationid ' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ' ORDER BY g.name';
    $host_groups = DBSelect($sql);
    while ($group = DBFetch($host_groups)) {
        $apps['ok'] = 0;
        $apps['failed'] = 0;
        $apps[HTTPTEST_STATE_BUSY] = 0;
        $apps[HTTPTEST_STATE_UNKNOWN] = 0;
        $sql = 'SELECT DISTINCT ht.httptestid, ht.curstate, ht.lastfailedstep ' . ' FROM httptest ht, applications a, hosts_groups hg, groups g ' . ' WHERE g.groupid=' . $group['groupid'] . ' AND hg.groupid=g.groupid ' . ' AND a.hostid=hg.hostid ' . ' AND ht.applicationid=a.applicationid ' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE;
        $db_httptests = DBselect($sql);
        while ($httptest_data = DBfetch($db_httptests)) {
            if (HTTPTEST_STATE_BUSY == $httptest_data['curstate']) {
                $apps[HTTPTEST_STATE_BUSY]++;
            } else {
                if (HTTPTEST_STATE_IDLE == $httptest_data['curstate']) {
                    if ($httptest_data['lastfailedstep'] > 0) {
                        $apps['failed']++;
                    } else {
                        $apps['ok']++;
                    }
                } else {
                    $apps[HTTPTEST_STATE_UNKNOWN]++;
                }
            }
        }
        $table->addRow(array(is_show_all_nodes() ? get_node_name_by_elid($group['groupid']) : null, $group['name'], new CSpan($apps['ok'], 'off'), new CSpan($apps['failed'], $apps['failed'] ? 'on' : 'off'), new CSpan($apps[HTTPTEST_STATE_BUSY], $apps[HTTPTEST_STATE_BUSY] ? 'orange' : 'off'), new CSpan($apps[HTTPTEST_STATE_UNKNOWN], 'unknown')));
    }
    $table->setFooter(new CCol(S_UPDATED . ': ' . date("H:i:s", time())));
    return $table;
}
コード例 #5
0
 /**
  * Inherit template graphs from template to host.
  *
  * @param array $data
  *
  * @return bool
  */
 public function syncTemplates($data)
 {
     $data['templateids'] = zbx_toArray($data['templateids']);
     $data['hostids'] = zbx_toArray($data['hostids']);
     $dbLinks = DBSelect('SELECT ht.hostid,ht.templateid' . ' FROM hosts_templates ht' . ' WHERE ' . dbConditionInt('ht.hostid', $data['hostids']) . ' AND ' . dbConditionInt('ht.templateid', $data['templateids']));
     $linkage = array();
     while ($link = DBfetch($dbLinks)) {
         if (!isset($linkage[$link['templateid']])) {
             $linkage[$link['templateid']] = array();
         }
         $linkage[$link['templateid']][$link['hostid']] = 1;
     }
     $graphs = $this->get(array('hostids' => $data['templateids'], 'preservekeys' => true, 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'selectHosts' => array('hostid'), 'filter' => array('flags' => null)));
     foreach ($graphs as $graph) {
         foreach ($data['hostids'] as $hostid) {
             if (isset($linkage[$graph['hosts'][0]['hostid']][$hostid])) {
                 $this->inherit($graph, $hostid);
             }
         }
     }
     return true;
 }
コード例 #6
0
ファイル: triggers.inc.php プロジェクト: rennhak/zabbix
function get_row_for_nofalseforb($row, $sql)
{
    $res_events = DBSelect($sql, 1);
    if (!($e_row = DBfetch($res_events))) {
        return false;
    } else {
        $row = array_merge($row, $e_row);
    }
    if ($row['value'] != TRIGGER_VALUE_TRUE && !event_initial_time($row)) {
        if (!($eventid = first_initial_eventid($row, 0))) {
            return false;
        }
        $sql = 'SELECT e.eventid, e.value' . ' FROM events e ' . ' WHERE e.eventid=' . $eventid . ' AND e.acknowledged=0';
        $res_events = DBSelect($sql, 1);
        if (!($e_row = DBfetch($res_events))) {
            return false;
        } else {
            $row = array_merge($row, $e_row);
        }
    }
    return $row;
}
コード例 #7
0
ファイル: hosts.inc.php プロジェクト: omidmt/zabbix-greenplum
/**
 * Returns the farthest host prototype ancestor for each given host prototype.
 *
 * @param array $hostPrototypeIds
 * @param array $templateHostPrototypeIds	array with parent host prototype IDs as keys and arrays of child host
 * 											prototype IDs as values
 *
 * @return array	an array of child ID - ancestor ID pairs
 */
function getHostPrototypeSourceParentIds(array $hostPrototypeIds, array $templateHostPrototypeIds = array())
{
    $query = DBSelect('SELECT h.hostid,h.templateid' . ' FROM hosts h' . ' WHERE ' . dbConditionInt('h.hostid', $hostPrototypeIds) . ' AND h.templateid>0');
    $hostPrototypeIds = array();
    while ($hostPrototype = DBfetch($query)) {
        // check if we already have host prototype inherited from the current host prototype
        // if we do - move all of its child prototypes to the parent template
        if (isset($templateHostPrototypeIds[$hostPrototype['hostid']])) {
            $templateHostPrototypeIds[$hostPrototype['templateid']] = $templateHostPrototypeIds[$hostPrototype['hostid']];
            unset($templateHostPrototypeIds[$hostPrototype['hostid']]);
        } else {
            $templateHostPrototypeIds[$hostPrototype['templateid']][] = $hostPrototype['hostid'];
            $hostPrototypeIds[] = $hostPrototype['templateid'];
        }
    }
    // continue while we still have new host prototypes to check
    if ($hostPrototypeIds) {
        return getHostPrototypeSourceParentIds($hostPrototypeIds, $templateHostPrototypeIds);
    } else {
        // return an inverse hash with prototype IDs as keys and parent prototype IDs as values
        $result = array();
        foreach ($templateHostPrototypeIds as $templateId => $hostIds) {
            foreach ($hostIds as $hostId) {
                $result[$hostId] = $templateId;
            }
        }
        return $result;
    }
}
コード例 #8
0
ファイル: DB.php プロジェクト: omidmt/zabbix-greenplum
 /**
  * Returns the records that match the given criteria.
  *
  * @static
  *
  * @param string $tableName
  * @param array $criteria   An associative array of field-value pairs, where value can be either a single value
  *                          or an array (IN)
  *
  * @return array
  */
 public static function find($tableName, array $criteria = array())
 {
     // build the WHERE part
     $sqlWhere = array();
     foreach ($criteria as $field => $value) {
         // check if the table has this field
         if (!self::hasField($tableName, $field)) {
             self::exception(self::DBEXECUTE_ERROR, _s('Table "%1$s" doesn\'t have a field named "%2$s".', $tableName, $field));
         }
         $sqlWhere[] = dbConditionString($field, zbx_toArray($value));
     }
     // build query
     $sql = 'SELECT * FROM ' . $tableName;
     if ($sqlWhere) {
         $sql .= ' WHERE ' . implode(' AND ', $sqlWhere);
     }
     return DBfetchArray(DBSelect($sql));
 }
コード例 #9
0
ファイル: resultados.php プロジェクト: markuz/planetalinux
	<caption>Resultados Concurso Planeta Linux 2007</caption>
	<thead>
		<tr>
			<th scope="col">Correo de Denunciante</th>
			<th scope="col">Puntos Acumulados</th>
		</tr>
	</thead>
	<tfoot>
		<tr>
			<th scope="row"></a></th>
			<td colspan="2"></td>									
		</tr>
	</tfoot>
	<tbody>		
       <?php 
$denunciantes = DBSelect("correo,puntos", "denunciantes", "", "Order by puntos DESC");
foreach ($denunciantes as $key => $denuncia) {
    echo "<tr class='odd'><th scope='row' id=denunciantes>" . $denuncia['correo'] . "</th>";
    echo " <td>" . $denuncia['puntos'] . "</td></tr>";
}
?>
  	</tbody>
	</table>	
	</div>
<?php 
require "footer.php";
?>
</body>
</html>

コード例 #10
0
ファイル: CTrigger.php プロジェクト: itnihao/Zabbix_
 /**
  * Check that none of the triggers have dependencies on their children. Checks only one level of inheritance, but
  * since it is called on each inheritance step, also works for multiple inheritance levels.
  *
  * @throws APIException     if at least one trigger is dependent on its child
  *
  * @param array $triggers
  */
 protected function checkDependencyParents(array $triggers)
 {
     // fetch all templated dependency trigger parents
     $depTriggerIds = array();
     foreach ($triggers as $trigger) {
         foreach ($trigger['dependencies'] as $depTriggerId) {
             $depTriggerIds[$depTriggerId] = $depTriggerId;
         }
     }
     $parentDepTriggers = DBfetchArray(DBSelect('SELECT templateid,triggerid' . ' FROM triggers' . ' WHERE templateid>0' . ' AND ' . dbConditionInt('triggerid', $depTriggerIds)));
     if ($parentDepTriggers) {
         $parentDepTriggers = zbx_toHash($parentDepTriggers, 'triggerid');
         foreach ($triggers as $trigger) {
             foreach ($trigger['dependencies'] as $depTriggerId) {
                 // check if the current trigger is the parent of the dependency trigger
                 if (isset($parentDepTriggers[$depTriggerId]) && $parentDepTriggers[$depTriggerId]['templateid'] == $trigger['triggerid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Trigger cannot be dependent on a trigger that is inherited from it.'));
                 }
             }
         }
     }
 }
コード例 #11
0
ファイル: forms.inc.php プロジェクト: rennhak/zabbix
function get_regexp_form()
{
    $frm_title = S_REGULAR_EXPRESSION;
    if (isset($_REQUEST['regexpid']) && !isset($_REQUEST["form_refresh"])) {
        $sql = 'SELECT re.* ' . ' FROM regexps re ' . ' WHERE ' . DBin_node('re.regexpid') . ' AND re.regexpid=' . $_REQUEST['regexpid'];
        $regexp = DBfetch(DBSelect($sql));
        $frm_title .= ' [' . $regexp['name'] . ']';
        $rename = $regexp['name'];
        $test_string = $regexp['test_string'];
        $expressions = array();
        $sql = 'SELECT e.* ' . ' FROM expressions e ' . ' WHERE ' . DBin_node('e.expressionid') . ' AND e.regexpid=' . $regexp['regexpid'] . ' ORDER BY e.expression_type';
        $db_exps = DBselect($sql);
        while ($exp = DBfetch($db_exps)) {
            $expressions[] = $exp;
        }
    } else {
        $rename = get_request('rename', '');
        $test_string = get_request('test_string', '');
        $expressions = get_request('expressions', array());
    }
    $tblRE = new CTable('', 'nowrap');
    $tblRE->addStyle('border-left: 1px #AAA solid; border-right: 1px #AAA solid; background-color: #EEE; padding: 2px; padding-left: 6px; padding-right: 6px;');
    $tblRE->addRow(array(S_NAME, new CTextBox('rename', $rename, 60)));
    $tblRE->addRow(array(S_TEST_STRING, new CTextArea('test_string', $test_string, 66, 5)));
    $tabExp = new CTableInfo();
    $td1 = new CCol(S_EXPRESSION);
    $td1->addStyle('background-color: #CCC;');
    $td2 = new CCol(S_EXPECTED_RESULT);
    $td2->addStyle('background-color: #CCC;');
    $td3 = new CCol(S_RESULT);
    $td3->addStyle('background-color: #CCC;');
    $tabExp->setHeader(array($td1, $td2, $td3));
    $final_result = !empty($test_string);
    foreach ($expressions as $id => $expression) {
        $results = array();
        $paterns = array($expression['expression']);
        if (!empty($test_string)) {
            if ($expression['expression_type'] == EXPRESSION_TYPE_ANY_INCLUDED) {
                $paterns = explode($expression['exp_delimiter'], $expression['expression']);
            }
            if (uint_in_array($expression['expression_type'], array(EXPRESSION_TYPE_TRUE, EXPRESSION_TYPE_FALSE))) {
                if ($expression['case_sensitive']) {
                    $results[$id] = ereg($paterns[0], $test_string);
                } else {
                    $results[$id] = eregi($paterns[0], $test_string);
                }
                if ($expression['expression_type'] == EXPRESSION_TYPE_TRUE) {
                    $final_result &= $results[$id];
                } else {
                    $final_result &= !$results[$id];
                }
            } else {
                $results[$id] = true;
                $tmp_result = false;
                if ($expression['case_sensitive']) {
                    foreach ($paterns as $pid => $patern) {
                        $tmp_result |= zbx_stristr($test_string, $patern) !== false;
                    }
                } else {
                    foreach ($paterns as $pid => $patern) {
                        $tmp_result |= zbx_strstr($test_string, $patern) !== false;
                    }
                }
                $results[$id] &= $tmp_result;
                $final_result &= $results[$id];
            }
        }
        if (isset($results[$id]) && $results[$id]) {
            $exp_res = new CSpan(S_TRUE_BIG, 'green bold');
        } else {
            $exp_res = new CSpan(S_FALSE_BIG, 'red bold');
        }
        $expec_result = expression_type2str($expression['expression_type']);
        if (EXPRESSION_TYPE_ANY_INCLUDED == $expression['expression_type']) {
            $expec_result .= ' (' . S_DELIMITER . "='" . $expression['exp_delimiter'] . "')";
        }
        $tabExp->addRow(array($expression['expression'], $expec_result, $exp_res));
    }
    $td = new CCol(S_COMBINED_RESULT, 'bold');
    $td->setColSpan(2);
    if ($final_result) {
        $final_result = new CSpan(S_TRUE_BIG, 'green bold');
    } else {
        $final_result = new CSpan(S_FALSE_BIG, 'red bold');
    }
    $tabExp->addRow(array($td, $final_result));
    $tblRE->addRow(array(S_RESULT, $tabExp));
    $tblFoot = new CTableInfo(null);
    $td = new CCol(array(new CButton('save', S_SAVE)));
    $td->setColSpan(2);
    $td->addStyle('text-align: right;');
    $td->addItem(SPACE);
    $td->addItem(new CButton('test', S_TEST));
    if (isset($_REQUEST['regexpid'])) {
        $td->addItem(SPACE);
        $td->addItem(new CButton('clone', S_CLONE));
        $td->addItem(SPACE);
        $td->addItem(new CButtonDelete(S_DELETE_REGULAR_EXPRESSION_Q, url_param('form') . url_param('config') . url_param('regexpid')));
    }
    $td->addItem(SPACE);
    $td->addItem(new CButtonCancel(url_param("regexpid")));
    $tblFoot->SetFooter($td);
    return array($tblRE, $tblFoot);
}
コード例 #12
0
function addUserHistory($title, $url)
{
    $userId = CWebUser::$data['userid'];
    $history5 = DBfetch(DBSelect('SELECT uh.title5,uh.url5' . ' FROM user_history uh' . ' WHERE uh.userid=' . $userId));
    if ($history5) {
        if ($history5['title5'] === $title) {
            if ($history5['url5'] === $url) {
                return true;
            } else {
                $sql = 'UPDATE user_history SET url5=' . zbx_dbstr($url) . ' WHERE userid=' . $userId;
            }
        } else {
            $sql = 'UPDATE user_history' . ' SET title1=title2,' . ' url1=url2,' . ' title2=title3,' . ' url2=url3,' . ' title3=title4,' . ' url3=url4,' . ' title4=title5,' . ' url4=url5,' . ' title5=' . zbx_dbstr($title) . ',' . ' url5=' . zbx_dbstr($url) . ' WHERE userid=' . $userId;
        }
    } else {
        $userHistoryId = get_dbid('user_history', 'userhistoryid');
        $sql = 'INSERT INTO user_history (userhistoryid, userid, title5, url5)' . ' VALUES(' . $userHistoryId . ', ' . $userId . ', ' . zbx_dbstr($title) . ', ' . zbx_dbstr($url) . ')';
    }
    return DBexecute($sql);
}
コード例 #13
0
 /**
  * Returns the value of the latest service alarm before the given time.
  *
  * @param array $serviceIds
  * @param int $beforeTime
  *
  * @return array
  */
 protected function fetchLatestValues(array $serviceIds, $beforeTime)
 {
     // the query will return the alarms with the maximum timestamp for each service
     // since multiple alarms can have the same timestamp, we only need to save the last one
     $query = DBSelect('SELECT sa.serviceid,sa.value' . ' FROM (SELECT MAX(sa3.servicealarmid) AS servicealarmid' . ' FROM (SELECT sa2.serviceid,MAX(sa2.clock) AS clock' . ' FROM service_alarms sa2' . ' WHERE sa2.clock<' . zbx_dbstr($beforeTime) . ' AND ' . dbConditionInt('sa2.serviceid', $serviceIds) . ' GROUP BY sa2.serviceid) ss' . ' JOIN service_alarms sa3 ON sa3.serviceid = ss.serviceid and sa3.clock = ss.clock' . ' GROUP BY sa3.serviceid) ss2' . ' JOIN service_alarms sa ON sa.servicealarmid = ss2.servicealarmid');
     $rs = array();
     while ($alarm = DBfetch($query)) {
         $rs[$alarm['serviceid']] = $alarm['value'];
     }
     return $rs;
 }
コード例 #14
0
$fields = array('regexpids' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'regexpid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, 'isset({form})&&({form}=="update")'), 'rename' => array(T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({save})', _('Name')), 'test_string' => array(T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({save})', _('Test string')), 'delete_regexp' => array(T_ZBX_STR, O_OPT, null, null, null), 'g_expressionid' => array(T_ZBX_INT, O_OPT, null, DB_ID, null), 'expressions' => array(T_ZBX_STR, O_OPT, null, null, 'isset({save})'), 'new_expression' => array(T_ZBX_STR, O_OPT, null, null, null), 'cancel_new_expression' => array(T_ZBX_STR, O_OPT, null, null, null), 'add_expression' => array(T_ZBX_STR, O_OPT, null, null, null), 'edit_expressionid' => array(T_ZBX_STR, O_OPT, null, null, null), 'delete_expression' => array(T_ZBX_STR, O_OPT, null, null, null), 'save' => array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, null), 'delete' => array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, null), 'clone' => array(T_ZBX_STR, O_OPT, null, null, null), 'go' => array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, null), 'form' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'form_refresh' => array(T_ZBX_INT, O_OPT, null, null, null));
check_fields($fields);
/*
 * Permissions
 */
if (isset($_REQUEST['regexpid'])) {
    $regExp = DBfetch(DBSelect('SELECT re.regexpid FROM regexps re WHERE re.regexpid=' . get_request('regexpid')));
    if (empty($regExp)) {
        access_deny();
    }
}
if (isset($_REQUEST['go']) && !isset($_REQUEST['regexpid'])) {
    if (!isset($_REQUEST['regexpids']) || !is_array($_REQUEST['regexpids'])) {
        access_deny();
    } else {
        $regExpChk = DBfetch(DBSelect('SELECT COUNT(*) AS cnt FROM regexps re WHERE ' . dbConditionInt('re.regexpid', $_REQUEST['regexpids'])));
        if ($regExpChk['cnt'] != count($_REQUEST['regexpids'])) {
            access_deny();
        }
    }
}
/*
 * Actions
 */
if (isset($_REQUEST['clone']) && isset($_REQUEST['regexpid'])) {
    unset($_REQUEST['regexpid']);
    $_REQUEST['form'] = 'clone';
} elseif (isset($_REQUEST['cancel_new_expression'])) {
    unset($_REQUEST['new_expression']);
} elseif (isset($_REQUEST['save'])) {
    $regExp = array('name' => $_REQUEST['rename'], 'test_string' => $_REQUEST['test_string']);
コード例 #15
0
function get_screen($screenid, $editmode, $effectiveperiod = NULL)
{
    global $USER_DETAILS;
    if ($screenid == 0) {
        return new CTableInfo(S_NO_SCREENS_DEFINED);
    }
    $r = CScreen::get(array('screenids' => $screenid, 'editable' => $editmode == 1 ? 1 : null, 'output' => API_OUTPUT_SHORTEN));
    if (empty($r)) {
        access_deny();
    }
    if (is_null($effectiveperiod)) {
        $effectiveperiod = ZBX_MIN_PERIOD;
    }
    $result = DBselect('SELECT name,hsize,vsize FROM screens WHERE screenid=' . $screenid);
    $row = DBfetch($result);
    if (!$row) {
        return new CTableInfo(S_NO_SCREENS_DEFINED);
    }
    $sql = 'SELECT * FROM screens_items WHERE screenid=' . $screenid;
    $iresult = DBSelect($sql);
    $skip_field = array();
    $irows = array();
    while ($irow = DBfetch($iresult)) {
        $irows[] = $irow;
        for ($i = 0; $i < $irow['rowspan'] || $i == 0; $i++) {
            for ($j = 0; $j < $irow['colspan'] || $j == 0; $j++) {
                if ($i != 0 || $j != 0) {
                    if (!isset($skip_field[$irow['y'] + $i])) {
                        $skip_field[$irow['y'] + $i] = array();
                    }
                    $skip_field[$irow['y'] + $i][$irow['x'] + $j] = 1;
                }
            }
        }
    }
    $table = new CTable(new CLink(S_NO_ROWS_IN_SCREEN . SPACE . $row['name'], 'screenconf.php?config=0&form=update&screenid=' . $screenid), $editmode == 0 || $editmode == 2 ? 'screen_view' : 'screen_edit');
    $table->setAttribute('id', 'iframe');
    if ($editmode == 1) {
        $new_cols = array(new Ccol(new Cimg('images/general/zero.gif', 'zero', 1, 1)));
        for ($c = 0; $c < $row['hsize'] + 1; $c++) {
            $add_icon = new Cimg('images/general/closed.gif', NULL, NULL, NULL, 'pointer');
            $add_icon->addAction('onclick', "javascript: location.href = 'screenedit.php?config=1&screenid={$screenid}&add_col={$c}';");
            array_push($new_cols, new Ccol($add_icon));
        }
        $table->addRow($new_cols);
    }
    $empty_screen_col = array();
    for ($r = 0; $r < $row['vsize']; $r++) {
        $new_cols = array();
        $empty_screen_row = true;
        if ($editmode == 1) {
            $add_icon = new Cimg('images/general/closed.gif', NULL, NULL, NULL, 'pointer');
            $add_icon->addAction('onclick', "javascript: location.href = 'screenedit.php?config=1&screenid={$screenid}&add_row={$r}';");
            array_push($new_cols, new Ccol($add_icon));
        }
        for ($c = 0; $c < $row['hsize']; $c++) {
            $item = array();
            if (isset($skip_field[$r][$c])) {
                continue;
            }
            $item_form = false;
            $irow = false;
            foreach ($irows as $tmprow) {
                if ($tmprow['x'] == $c && $tmprow['y'] == $r) {
                    $irow = $tmprow;
                    break;
                }
            }
            if ($irow) {
                $screenitemid = $irow['screenitemid'];
                $resourcetype = $irow['resourcetype'];
                $resourceid = $irow['resourceid'];
                $width = $irow['width'];
                $height = $irow['height'];
                $colspan = $irow['colspan'];
                $rowspan = $irow['rowspan'];
                $elements = $irow['elements'];
                $valign = $irow['valign'];
                $halign = $irow['halign'];
                $style = $irow['style'];
                $url = $irow['url'];
                $dynamic = $irow['dynamic'];
            } else {
                $screenitemid = 0;
                $resourcetype = 0;
                $resourceid = 0;
                $width = 0;
                $height = 0;
                $colspan = 0;
                $rowspan = 0;
                $elements = 0;
                $valign = VALIGN_DEFAULT;
                $halign = HALIGN_DEFAULT;
                $style = 0;
                $url = '';
                $dynamic = 0;
            }
            if ($screenitemid > 0) {
                $empty_screen_row = false;
                $empty_screen_col[$c] = 1;
            }
            if ($editmode == 1 && $screenitemid != 0) {
                $onclick_action = "ZBX_SCREENS['" . $_REQUEST['screenid'] . "'].screen.element_onclick('screenedit.php?form=update" . url_param('screenid') . '&screenitemid=' . $screenitemid . "#form');";
                $action = 'screenedit.php?form=update' . url_param('screenid') . '&screenitemid=' . $screenitemid . '#form';
            } else {
                if ($editmode == 1 && $screenitemid == 0) {
                    $onclick_action = "ZBX_SCREENS['" . $_REQUEST['screenid'] . "'].screen.element_onclick('screenedit.php?form=update" . url_param('screenid') . '&x=' . $c . '&y=' . $r . "#form');";
                    $action = 'screenedit.php?form=update' . url_param('screenid') . '&x=' . $c . '&y=' . $r . '#form';
                } else {
                    $action = NULL;
                }
            }
            if ($editmode == 1 && isset($_REQUEST['form']) && isset($_REQUEST['x']) && $_REQUEST['x'] == $c && isset($_REQUEST['y']) && $_REQUEST['y'] == $r) {
                // click on empty field
                $item = get_screen_item_form();
                $item_form = true;
            } else {
                if ($editmode == 1 && isset($_REQUEST['form']) && isset($_REQUEST['screenitemid']) && bccomp($_REQUEST['screenitemid'], $screenitemid) == 0) {
                    // click on element
                    $item = get_screen_item_form();
                    $item_form = true;
                } else {
                    if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_GRAPH) {
                        if ($editmode == 0) {
                            $action = 'charts.php?graphid=' . $resourceid . url_param('period') . url_param('stime');
                        }
                        // GRAPH & ZOOM features
                        $dom_graph_id = 'graph_' . $screenitemid . '_' . $resourceid;
                        $containerid = 'graph_cont_' . $screenitemid . '_' . $resourceid;
                        $graphDims = getGraphDims($resourceid);
                        $graphDims['graphHeight'] = $height;
                        $graphDims['width'] = $width;
                        $graph = get_graph_by_graphid($resourceid);
                        $graphid = $graph['graphid'];
                        $legend = $graph['show_legend'];
                        $graph3d = $graph['show_3d'];
                        //-------------
                        // Host feature
                        if ($dynamic == SCREEN_DYNAMIC_ITEM && isset($_REQUEST['hostid']) && $_REQUEST['hostid'] > 0) {
                            $options = array('hostids' => $_REQUEST['hostid'], 'output' => array('hostid', 'host'));
                            $hosts = CHost::get($options);
                            $host = reset($hosts);
                            $options = array('graphids' => $resourceid, 'output' => API_OUTPUT_EXTEND, 'select_hosts' => API_OUTPUT_REFER, 'select_graph_items' => API_OUTPUT_EXTEND);
                            $graph = CGraph::get($options);
                            $graph = reset($graph);
                            if (count($graph['hosts']) == 1) {
                                // if items from one host we change them, or set calculated if not exist on that host
                                if ($graph['ymax_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE && $graph['ymax_itemid']) {
                                    $new_dinamic = get_same_graphitems_for_host(array(array('itemid' => $graph['ymax_itemid'])), $_REQUEST['hostid'], false);
                                    $new_dinamic = reset($new_dinamic);
                                    if (isset($new_dinamic['itemid']) && $new_dinamic['itemid'] > 0) {
                                        $graph['ymax_itemid'] = $new_dinamic['itemid'];
                                    } else {
                                        $graph['ymax_type'] = GRAPH_YAXIS_TYPE_CALCULATED;
                                    }
                                }
                                if ($graph['ymin_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE && $graph['ymin_itemid']) {
                                    $new_dinamic = get_same_graphitems_for_host(array(array('itemid' => $graph['ymin_itemid'])), $_REQUEST['hostid'], false);
                                    $new_dinamic = reset($new_dinamic);
                                    if (isset($new_dinamic['itemid']) && $new_dinamic['itemid'] > 0) {
                                        $graph['ymin_itemid'] = $new_dinamic['itemid'];
                                    } else {
                                        $graph['ymin_type'] = GRAPH_YAXIS_TYPE_CALCULATED;
                                    }
                                }
                            }
                            $url = $graph['graphtype'] == GRAPH_TYPE_PIE || $graph['graphtype'] == GRAPH_TYPE_EXPLODED ? 'chart7.php' : 'chart3.php';
                            $url = new Curl($url);
                            foreach ($graph as $name => $value) {
                                if ($name == 'width' || $name == 'height') {
                                    continue;
                                }
                                $url->setArgument($name, $value);
                            }
                            $new_items = get_same_graphitems_for_host($graph['gitems'], $_REQUEST['hostid'], false);
                            foreach ($new_items as $gitem) {
                                unset($gitem['gitemid']);
                                unset($gitem['graphid']);
                                foreach ($gitem as $name => $value) {
                                    $url->setArgument('items[' . $gitem['itemid'] . '][' . $name . ']', $value);
                                }
                            }
                            $url->setArgument('name', $host['host'] . ': ' . $graph['name']);
                            $url = $url->getUrl();
                        }
                        //-------------
                        $objData = array('id' => $resourceid, 'domid' => $dom_graph_id, 'containerid' => $containerid, 'objDims' => $graphDims, 'loadSBox' => 0, 'loadImage' => 1, 'loadScroll' => 0, 'dynamic' => 0);
                        $default = false;
                        if ($graphDims['graphtype'] == GRAPH_TYPE_PIE || $graphDims['graphtype'] == GRAPH_TYPE_EXPLODED) {
                            if ($dynamic == SCREEN_SIMPLE_ITEM || empty($url)) {
                                $url = 'chart6.php?graphid=' . $resourceid;
                                $default = true;
                            }
                            $timeline = array();
                            $timeline['period'] = $effectiveperiod;
                            $timeline['starttime'] = date('YmdHis', get_min_itemclock_by_graphid($resourceid));
                            if (isset($_REQUEST['stime'])) {
                                $timeline['usertime'] = date('YmdHis', zbxDateToTime($_REQUEST['stime']) + $timeline['period']);
                            }
                            // $src = $url.'&width='.$width.'&height='.$height.'&legend='.$legend.'&graph3d='.$graph3d;
                            $src = $url . '&width=' . $width . '&height=' . $height . '&legend=' . $legend . '&graph3d=' . $graph3d . '&period=' . $effectiveperiod . url_param('stime');
                            $objData['src'] = $src;
                        } else {
                            if ($dynamic == SCREEN_SIMPLE_ITEM || empty($url)) {
                                $url = 'chart2.php?graphid=' . $resourceid;
                                $default = true;
                            }
                            $src = $url . '&width=' . $width . '&height=' . $height . '&period=' . $effectiveperiod . url_param('stime');
                            $timeline = array();
                            if (isset($graphid) && !is_null($graphid) && $editmode != 1) {
                                $timeline['period'] = $effectiveperiod;
                                $timeline['starttime'] = date('YmdHis', time() - ZBX_MAX_PERIOD);
                                //get_min_itemclock_by_graphid($graphid);
                                if (isset($_REQUEST['stime'])) {
                                    $timeline['usertime'] = date('YmdHis', zbxDateToTime($_REQUEST['stime']) + $timeline['period']);
                                }
                                $objData['loadSBox'] = 1;
                            }
                            $objData['src'] = $src;
                        }
                        if ($editmode || !$default) {
                            $item = new CDiv();
                        } else {
                            $item = new CLink(null, $action);
                        }
                        $item->setAttribute('id', $containerid);
                        $item = array($item);
                        if ($editmode == 1) {
                            $item[] = BR();
                            $item[] = new CLink(S_CHANGE, $action);
                        }
                        if ($editmode == 2) {
                            insert_js('timeControl.addObject("' . $dom_graph_id . '",' . zbx_jsvalue($timeline) . ',' . zbx_jsvalue($objData) . ');');
                        } else {
                            zbx_add_post_js('timeControl.addObject("' . $dom_graph_id . '",' . zbx_jsvalue($timeline) . ',' . zbx_jsvalue($objData) . ');');
                        }
                    } else {
                        if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_SIMPLE_GRAPH) {
                            $dom_graph_id = 'graph_' . $screenitemid . '_' . $resourceid;
                            $containerid = 'graph_cont_' . $screenitemid . '_' . $resourceid;
                            $graphDims = getGraphDims();
                            $graphDims['graphHeight'] = $height;
                            $graphDims['width'] = $width;
                            $objData = array('id' => $resourceid, 'domid' => $dom_graph_id, 'containerid' => $containerid, 'objDims' => $graphDims, 'loadSBox' => 0, 'loadImage' => 1, 'loadScroll' => 0, 'dynamic' => 0);
                            // Host feature
                            if ($dynamic == SCREEN_DYNAMIC_ITEM && isset($_REQUEST['hostid']) && $_REQUEST['hostid'] > 0) {
                                if ($newitemid = get_same_item_for_host($resourceid, $_REQUEST['hostid'])) {
                                    $resourceid = $newitemid;
                                } else {
                                    $resourceid = '';
                                }
                            }
                            //-------------
                            if ($editmode == 0 && !empty($resourceid)) {
                                $action = 'history.php?action=showgraph&itemid=' . $resourceid . url_param('period') . url_param('stime');
                            }
                            $timeline = array();
                            $timeline['starttime'] = date('YmdHis', time() - ZBX_MAX_PERIOD);
                            if (!zbx_empty($resourceid) && $editmode != 1) {
                                $timeline['period'] = $effectiveperiod;
                                if (isset($_REQUEST['stime'])) {
                                    $timeline['usertime'] = date('YmdHis', zbxDateToTime($_REQUEST['stime']) + $timeline['period']);
                                }
                                $objData['loadSBox'] = 1;
                            }
                            $src = zbx_empty($resourceid) ? 'chart3.php?' : 'chart.php?itemid=' . $resourceid . '&';
                            $src .= $url . 'width=' . $width . '&height=' . $height;
                            $objData['src'] = $src;
                            if ($editmode) {
                                $item = new CDiv();
                            } else {
                                $item = new CLink(null, $action);
                            }
                            $item->setAttribute('id', $containerid);
                            $item = array($item);
                            if ($editmode == 1) {
                                $item[] = BR();
                                $item[] = new CLink(S_CHANGE, $action);
                            }
                            if ($editmode == 2) {
                                insert_js('timeControl.addObject("' . $dom_graph_id . '",' . zbx_jsvalue($timeline) . ',' . zbx_jsvalue($objData) . ');');
                            } else {
                                zbx_add_post_js('timeControl.addObject("' . $dom_graph_id . '",' . zbx_jsvalue($timeline) . ',' . zbx_jsvalue($objData) . ');');
                            }
                        } else {
                            if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_MAP) {
                                $image_map = new CImg("map.php?noedit=1&sysmapid={$resourceid}" . "&width={$width}&height={$height}&curtime=" . time());
                                if ($editmode == 0) {
                                    $options = array('sysmapids' => $resourceid, 'output' => API_OUTPUT_EXTEND, 'select_selements' => API_OUTPUT_EXTEND, 'nopermissions' => 1);
                                    $sysmaps = CMap::get($options);
                                    $sysmap = reset($sysmaps);
                                    $action_map = getActionMapBySysmap($sysmap);
                                    $image_map->setMap($action_map->getName());
                                    $item = array($action_map, $image_map);
                                } else {
                                    $item = $image_map;
                                    //						$item = new CLink($image_map, $action);
                                }
                            } else {
                                if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_PLAIN_TEXT) {
                                    // Host feature
                                    if ($dynamic == SCREEN_DYNAMIC_ITEM && isset($_REQUEST['hostid']) && $_REQUEST['hostid'] > 0) {
                                        if ($newitemid = get_same_item_for_host($resourceid, $_REQUEST['hostid'])) {
                                            $resourceid = $newitemid;
                                        } else {
                                            $resourceid = 0;
                                        }
                                    }
                                    //-------------
                                    $item = array(get_screen_plaintext($resourceid, $elements, $style));
                                    if ($editmode == 1) {
                                        array_push($item, new CLink(S_CHANGE, $action));
                                    }
                                } else {
                                    if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_HOSTGROUP_TRIGGERS) {
                                        $params = array('groupids' => null, 'hostids' => null, 'maintenance' => null, 'severity' => null, 'limit' => $elements);
                                        $tr_form = S_ALL_S;
                                        if ($resourceid > 0) {
                                            $options = array('groupids' => $resourceid, 'output' => API_OUTPUT_EXTEND);
                                            $hostgroups = CHostgroup::get($options);
                                            $hostgroup = reset($hostgroups);
                                            $tr_form = new CSpan(S_GROUP . ': ' . $hostgroup['name'], 'white');
                                            $params['groupids'] = $hostgroup['groupid'];
                                        } else {
                                            $groupid = get_request('tr_groupid', CProfile::get('web.screens.tr_groupid', 0));
                                            $hostid = get_request('tr_hostid', CProfile::get('web.screens.tr_hostid', 0));
                                            CProfile::update('web.screens.tr_groupid', $groupid, PROFILE_TYPE_ID);
                                            CProfile::update('web.screens.tr_hostid', $hostid, PROFILE_TYPE_ID);
                                            $options = array('monitored_hosts' => 1, 'output' => API_OUTPUT_EXTEND);
                                            $groups = CHostGroup::get($options);
                                            order_result($groups, 'name');
                                            $options = array('monitored_hosts' => 1, 'output' => API_OUTPUT_EXTEND);
                                            if ($groupid > 0) {
                                                $options['groupids'] = $groupid;
                                            }
                                            $hosts = CHost::get($options);
                                            $hosts = zbx_toHash($hosts, 'hostid');
                                            order_result($hosts, 'host');
                                            if (!isset($hosts[$hostid])) {
                                                $hostid = 0;
                                            }
                                            $tr_form = new CForm();
                                            $cmbGroup = new CComboBox('tr_groupid', $groupid, 'submit()');
                                            $cmbHosts = new CComboBox('tr_hostid', $hostid, 'submit()');
                                            $cmbGroup->addItem(0, S_ALL_SMALL);
                                            $cmbHosts->addItem(0, S_ALL_SMALL);
                                            foreach ($groups as $gnum => $group) {
                                                $cmbGroup->addItem($group['groupid'], get_node_name_by_elid($group['groupid'], null, ': ') . $group['name']);
                                            }
                                            foreach ($hosts as $hnum => $host) {
                                                $cmbHosts->addItem($host['hostid'], get_node_name_by_elid($host['hostid'], null, ': ') . $host['host']);
                                            }
                                            $tr_form->addItem(array(S_GROUP . SPACE, $cmbGroup));
                                            $tr_form->addItem(array(SPACE . S_HOST . SPACE, $cmbHosts));
                                            if ($groupid > 0) {
                                                $params['groupids'] = $groupid;
                                            }
                                            if ($hostid > 0) {
                                                $params['hostids'] = $hostid;
                                            }
                                        }
                                        $item = array(get_table_header(array(S_STATUS_OF_TRIGGERS_BIG, SPACE, zbx_date2str(S_SCREENS_TRIGGER_FORM_DATE_FORMAT)), $tr_form));
                                        $item[] = make_latest_issues($params);
                                        if ($editmode == 1) {
                                            array_push($item, new CLink(S_CHANGE, $action));
                                        }
                                        ///-----------------------
                                    } else {
                                        if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_HOST_TRIGGERS) {
                                            $params = array('groupids' => null, 'hostids' => null, 'maintenance' => null, 'severity' => null, 'limit' => $elements);
                                            $tr_form = S_ALL_S;
                                            if ($resourceid > 0) {
                                                $options = array('hostids' => $resourceid, 'output' => API_OUTPUT_EXTEND);
                                                $hosts = CHost::get($options);
                                                $host = reset($hosts);
                                                $tr_form = new CSpan(S_HOST . ': ' . $host['host'], 'white');
                                                $params['hostids'] = $host['hostid'];
                                            } else {
                                                $groupid = get_request('tr_groupid', CProfile::get('web.screens.tr_groupid', 0));
                                                $hostid = get_request('tr_hostid', CProfile::get('web.screens.tr_hostid', 0));
                                                CProfile::update('web.screens.tr_groupid', $groupid, PROFILE_TYPE_ID);
                                                CProfile::update('web.screens.tr_hostid', $hostid, PROFILE_TYPE_ID);
                                                $options = array('monitored_hosts' => 1, 'output' => API_OUTPUT_EXTEND);
                                                $groups = CHostGroup::get($options);
                                                order_result($groups, 'name');
                                                $options = array('monitored_hosts' => 1, 'output' => API_OUTPUT_EXTEND);
                                                if ($groupid > 0) {
                                                    $options['groupids'] = $groupid;
                                                }
                                                $hosts = CHost::get($options);
                                                $hosts = zbx_toHash($hosts, 'hostid');
                                                order_result($hosts, 'host');
                                                if (!isset($hosts[$hostid])) {
                                                    $hostid = 0;
                                                }
                                                $tr_form = new CForm();
                                                $cmbGroup = new CComboBox('tr_groupid', $groupid, 'submit()');
                                                $cmbHosts = new CComboBox('tr_hostid', $hostid, 'submit()');
                                                $cmbGroup->addItem(0, S_ALL_SMALL);
                                                $cmbHosts->addItem(0, S_ALL_SMALL);
                                                foreach ($groups as $gnum => $group) {
                                                    $cmbGroup->addItem($group['groupid'], get_node_name_by_elid($group['groupid'], null, ': ') . $group['name']);
                                                }
                                                foreach ($hosts as $hnum => $host) {
                                                    $cmbHosts->addItem($host['hostid'], get_node_name_by_elid($host['hostid'], null, ': ') . $host['host']);
                                                }
                                                $tr_form->addItem(array(S_GROUP . SPACE, $cmbGroup));
                                                $tr_form->addItem(array(SPACE . S_HOST . SPACE, $cmbHosts));
                                                if ($groupid > 0) {
                                                    $params['groupids'] = $groupid;
                                                }
                                                if ($hostid > 0) {
                                                    $params['hostids'] = $hostid;
                                                }
                                            }
                                            ///-----------------------
                                            $item = array(get_table_header(array(S_STATUS_OF_TRIGGERS_BIG, SPACE, zbx_date2str(S_SCREENS_TRIGGER_FORM_DATE_FORMAT)), $tr_form));
                                            $item[] = make_latest_issues($params);
                                            if ($editmode == 1) {
                                                array_push($item, new CLink(S_CHANGE, $action));
                                            }
                                        } else {
                                            if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_SYSTEM_STATUS) {
                                                $params = array('groupids' => null, 'hostids' => null, 'maintenance' => null, 'severity' => null, 'limit' => null, 'extAck' => 0);
                                                $item = array(get_table_header(array(S_SYSTEM_STATUS, SPACE, zbx_date2str(S_SCREENS_TRIGGER_FORM_DATE_FORMAT))));
                                                $item[] = make_system_status($params);
                                                if ($editmode == 1) {
                                                    array_push($item, new CLink(S_CHANGE, $action));
                                                }
                                            } else {
                                                if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_HOSTS_INFO) {
                                                    $item = array(new CHostsInfo($resourceid, $style));
                                                    if ($editmode == 1) {
                                                        array_push($item, new CLink(S_CHANGE, $action));
                                                    }
                                                } else {
                                                    if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_TRIGGERS_INFO) {
                                                        $item = new CTriggersInfo($resourceid, null, $style);
                                                        $item = array($item);
                                                        if ($editmode == 1) {
                                                            array_push($item, new CLink(S_CHANGE, $action));
                                                        }
                                                    } else {
                                                        if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_SERVER_INFO) {
                                                            //					$item = array(get_table_header(S_STATUS_OF_ZABBIX_BIG),make_status_of_zbx());
                                                            $item = array(new CServerInfo());
                                                            if ($editmode == 1) {
                                                                array_push($item, new CLink(S_CHANGE, $action));
                                                            }
                                                        } else {
                                                            if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_CLOCK) {
                                                                $item = new CFlashClock($width, $height, $style, $action);
                                                            } else {
                                                                if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_SCREEN) {
                                                                    $item = array(get_screen($resourceid, 2, $effectiveperiod));
                                                                    if ($editmode == 1) {
                                                                        array_push($item, new CLink(S_CHANGE, $action));
                                                                    }
                                                                } else {
                                                                    if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_TRIGGERS_OVERVIEW) {
                                                                        $hostids = array();
                                                                        $res = DBselect('SELECT DISTINCT hg.hostid FROM hosts_groups hg WHERE hg.groupid=' . $resourceid);
                                                                        while ($tmp_host = DBfetch($res)) {
                                                                            $hostids[$tmp_host['hostid']] = $tmp_host['hostid'];
                                                                        }
                                                                        $item = array(get_triggers_overview($hostids, $style));
                                                                        if ($editmode == 1) {
                                                                            array_push($item, new CLink(S_CHANGE, $action));
                                                                        }
                                                                    } else {
                                                                        if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_DATA_OVERVIEW) {
                                                                            $hostids = array();
                                                                            $res = DBselect('SELECT DISTINCT hg.hostid FROM hosts_groups hg WHERE hg.groupid=' . $resourceid);
                                                                            while ($tmp_host = DBfetch($res)) {
                                                                                $hostids[$tmp_host['hostid']] = $tmp_host['hostid'];
                                                                            }
                                                                            $item = array(get_items_data_overview($hostids, $style));
                                                                            if ($editmode == 1) {
                                                                                array_push($item, new CLink(S_CHANGE, $action));
                                                                            }
                                                                        } else {
                                                                            if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_URL) {
                                                                                $item = array(new CIFrame($url, $width, $height, "auto"));
                                                                                if ($editmode == 1) {
                                                                                    array_push($item, BR(), new CLink(S_CHANGE, $action));
                                                                                }
                                                                            } else {
                                                                                if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_ACTIONS) {
                                                                                    $item = array(get_history_of_actions($elements));
                                                                                    if ($editmode == 1) {
                                                                                        array_push($item, new CLink(S_CHANGE, $action));
                                                                                    }
                                                                                } else {
                                                                                    if ($screenitemid != 0 && $resourcetype == SCREEN_RESOURCE_EVENTS) {
                                                                                        $options = array('monitored' => 1, 'value' => array(TRIGGER_VALUE_TRUE, TRIGGER_VALUE_FALSE), 'limit' => $elements);
                                                                                        $hide_unknown = CProfile::get('web.events.filter.hide_unknown', 0);
                                                                                        if ($hide_unknown) {
                                                                                            $options['value'] = array(TRIGGER_VALUE_TRUE, TRIGGER_VALUE_FALSE);
                                                                                        }
                                                                                        $item = new CTableInfo(S_NO_EVENTS_FOUND);
                                                                                        $item->SetHeader(array(S_TIME, is_show_all_nodes() ? S_NODE : null, S_HOST, S_DESCRIPTION, S_VALUE, S_SEVERITY));
                                                                                        $events = getLastEvents($options);
                                                                                        foreach ($events as $enum => $event) {
                                                                                            $trigger = $event['trigger'];
                                                                                            $host = $event['host'];
                                                                                            $value = new CCol(trigger_value2str($event['value']), get_trigger_value_style($event['value']));
                                                                                            //						$row = zbx_array_merge($triggers[$row['triggerid']],$row);
                                                                                            //						if((1 == $hide_unknown) && (!event_initial_time($row,$hide_unknown))) continue;
                                                                                            $item->addRow(array(zbx_date2str(S_EVENTS_TRIGGERS_EVENTS_HISTORY_LIST_DATE_FORMAT, $event['clock']), get_node_name_by_elid($event['objectid']), $host['host'], new CLink($trigger['description'], 'tr_events.php?triggerid=' . $event['objectid'] . '&eventid=' . $event['eventid']), $value, new CCol(get_severity_description($trigger['priority']), get_severity_style($trigger['priority']))));
                                                                                        }
                                                                                        $item = array($item);
                                                                                        if ($editmode == 1) {
                                                                                            array_push($item, new CLink(S_CHANGE, $action));
                                                                                        }
                                                                                    } else {
                                                                                        $item = array(SPACE);
                                                                                        if ($editmode == 1) {
                                                                                            array_push($item, BR(), new CLink(S_CHANGE, $action));
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $str_halign = 'def';
            if ($halign == HALIGN_CENTER) {
                $str_halign = 'cntr';
            }
            if ($halign == HALIGN_LEFT) {
                $str_halign = 'left';
            }
            if ($halign == HALIGN_RIGHT) {
                $str_halign = 'right';
            }
            $str_valign = 'def';
            if ($valign == VALIGN_MIDDLE) {
                $str_valign = 'mdl';
            }
            if ($valign == VALIGN_TOP) {
                $str_valign = 'top';
            }
            if ($valign == VALIGN_BOTTOM) {
                $str_valign = 'bttm';
            }
            if ($editmode == 1 && !$item_form) {
                $item = new CDiv($item, 'draggable');
                $item->setAttribute('id', 'position_' . $r . '_' . $c);
                if ($editmode == 1) {
                    $item->setAttribute('onclick', 'javascript: ' . $onclick_action);
                }
            }
            $new_col = new CCol($item, $str_halign . '_' . $str_valign);
            if ($colspan) {
                $new_col->SetColSpan($colspan);
            }
            if ($rowspan) {
                $new_col->SetRowSpan($rowspan);
            }
            array_push($new_cols, $new_col);
        }
        if ($editmode == 1) {
            $rmv_icon = new Cimg('images/general/opened.gif', NULL, NULL, NULL, 'pointer');
            if ($empty_screen_row) {
                $rmv_row_link = "javascript: location.href = 'screenedit.php?config=1&screenid={$screenid}&rmv_row={$r}';";
            } else {
                $rmv_row_link = "javascript: if(Confirm('" . S_THIS_SCREEN_ROW_NOT_EMPTY . '. ' . S_DELETE_IT_Q . "')){" . " location.href = 'screenedit.php?config=1&screenid={$screenid}&rmv_row={$r}';}";
            }
            $rmv_icon->addAction('onclick', $rmv_row_link);
            array_push($new_cols, new Ccol($rmv_icon));
        }
        $table->addRow(new CRow($new_cols));
    }
    if ($editmode == 1) {
        $add_icon = new Cimg('images/general/closed.gif', NULL, NULL, NULL, 'pointer');
        $add_icon->addAction('onclick', "javascript: location.href = 'screenedit.php?config=1&screenid={$screenid}&add_row={$row['vsize']}';");
        $new_cols = array(new Ccol($add_icon));
        for ($c = 0; $c < $row['hsize']; $c++) {
            $rmv_icon = new Cimg('images/general/opened.gif', NULL, NULL, NULL, 'pointer');
            if (isset($empty_screen_col[$c])) {
                $rmv_col_link = "javascript: if(Confirm('" . S_THIS_SCREEN_COLUMN_NOT_EMPTY . '. ' . S_DELETE_IT_Q . "')){" . " location.href = 'screenedit.php?config=1&screenid={$screenid}&rmv_col={$c}';}";
            } else {
                $rmv_col_link = "javascript: location.href = 'screenedit.php?config=1&screenid={$screenid}&rmv_col={$c}';";
            }
            $rmv_icon->addAction('onclick', $rmv_col_link);
            array_push($new_cols, new Ccol($rmv_icon));
        }
        array_push($new_cols, new Ccol(new Cimg('images/general/zero.gif', 'zero', 1, 1)));
        $table->addRow($new_cols);
    }
    return $table;
}
コード例 #16
0
 /**
  * Check that none of the triggers have dependencies on their children. Checks only one level of inheritance, but
  * since it is called on each inheritance step, also works for multiple inheritance levels.
  *
  * @param array  $triggerPrototypes
  * @param string $triggerPrototypes[]['triggerid']
  * @param array  $triggerPrototypes[]['dependencies']
  * @param string $triggerPrototypes[]['dependencies'][]['triggerid']
  *
  * @throws APIException if at least one trigger is dependent on its child.
  */
 protected function checkDependencyParents(array $triggerPrototypes)
 {
     // fetch all templated dependency trigger parents
     $depTriggerIds = [];
     foreach ($triggerPrototypes as $triggerPrototype) {
         if (!array_key_exists('dependencies', $triggerPrototype)) {
             continue;
         }
         foreach ($triggerPrototype['dependencies'] as $dependency) {
             $depTriggerIds[$dependency['triggerid']] = $dependency['triggerid'];
         }
     }
     $parentDepTriggers = DBfetchArray(DBSelect('SELECT templateid,triggerid' . ' FROM triggers' . ' WHERE templateid>0' . ' AND ' . dbConditionInt('triggerid', $depTriggerIds)));
     if ($parentDepTriggers) {
         $parentDepTriggers = zbx_toHash($parentDepTriggers, 'triggerid');
         foreach ($triggerPrototypes as $triggerPrototype) {
             foreach ($triggerPrototype['dependencies'] as $dependency) {
                 // Check if the current trigger is the parent of the dependency trigger.
                 $depTriggerId = $dependency['triggerid'];
                 if (isset($parentDepTriggers[$depTriggerId]) && $parentDepTriggers[$depTriggerId]['templateid'] == $triggerPrototype['triggerid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Trigger prototype cannot be dependent on a trigger that is inherited from it.'));
                 }
             }
         }
     }
 }
コード例 #17
0
 /**
  * Constructs an SQL SELECT query for a specific table from the given API options, executes it and returns
  * the result.
  *
  * TODO: add global 'countOutput' support
  *
  * @param string $tableName
  * @param array $options
  *
  * @return array
  */
 protected function select($tableName, array $options)
 {
     $limit = isset($options['limit']) ? $options['limit'] : null;
     $sql = $this->createSelectQuery($tableName, $options);
     $query = DBSelect($sql, $limit);
     $objects = DBfetchArray($query);
     if (isset($options['preservekeys'])) {
         $rs = array();
         foreach ($objects as $object) {
             $rs[$object[$this->pk($tableName)]] = $this->unsetExtraFields($tableName, $object, $options['output']);
         }
         return $rs;
     } else {
         return $objects;
     }
 }
コード例 #18
0
 /**
  * Checks if the given host prototypes are not inherited from a template.
  *
  * @throws APIException 	if at least one host prototype is inherited
  *
  * @param array $hostPrototypeIds
  */
 protected function checkNotInherited(array $hostPrototypeIds)
 {
     $query = DBSelect('SELECT hostid FROM hosts h WHERE h.templateid>0 AND ' . dbConditionInt('h.hostid', $hostPrototypeIds), 1);
     if ($hostPrototype = DBfetch($query)) {
         self::exception(ZBX_API_ERROR_PERMISSIONS, _('Cannot delete templated host prototype.'));
     }
 }
コード例 #19
0
ファイル: CTrigger.php プロジェクト: jbfavre/debian-zabbix
 protected function applyPostSqlFiltering(array $triggers, array $options)
 {
     $triggers = zbx_toHash($triggers, 'triggerid');
     // unset triggers which depend on at least one problem trigger upstream into dependency tree
     if ($options['skipDependent'] !== null) {
         // Result trigger IDs of all triggers in results.
         $resultTriggerIds = zbx_objectValues($triggers, 'triggerid');
         // Will contain IDs of all triggers on which some other trigger depends.
         $allUpTriggerIds = [];
         // Trigger dependency map.
         $downToUpTriggerIds = [];
         // Values (state) of each "up" trigger ID is stored in here.
         $upTriggerValues = [];
         // Will contain IDs of all triggers either disabled directly, or by having disabled item or disabled host.
         $disabledTriggerIds = [];
         // First loop uses result trigger IDs.
         $triggerIds = $resultTriggerIds;
         do {
             // Fetch all dependency records where "down" trigger IDs are in current iteration trigger IDs.
             $dbResult = DBselect('SELECT d.triggerid_down,d.triggerid_up,t.value' . ' FROM trigger_depends d,triggers t' . ' WHERE d.triggerid_up=t.triggerid' . ' AND ' . dbConditionInt('d.triggerid_down', $triggerIds));
             // Add trigger IDs as keys and empty arrays as values.
             $downToUpTriggerIds = $downToUpTriggerIds + array_fill_keys($triggerIds, []);
             $triggerIds = [];
             while ($dependency = DBfetch($dbResult)) {
                 // Trigger ID for "down" trigger, which has dependencies.
                 $downTriggerId = $dependency['triggerid_down'];
                 // Trigger ID for "up" trigger, on which the other ("up") trigger depends.
                 $upTriggerId = $dependency['triggerid_up'];
                 // Add "up" trigger ID to mapping. We also index by $upTrigger because later these arrays
                 // are combined with + and this way indexes and values do not break.
                 $downToUpTriggerIds[$downTriggerId][$upTriggerId] = $upTriggerId;
                 // Add ID of this "up" trigger to all known "up" triggers.
                 $allUpTriggerIds[] = $upTriggerId;
                 // Remember value of this "up" trigger.
                 $upTriggerValues[$upTriggerId] = $dependency['value'];
                 // Add ID of this "up" trigger to the list of trigger IDs which should be mapped.
                 $triggerIds[] = $upTriggerId;
             }
         } while ($triggerIds);
         // Fetch trigger IDs for triggers that are disabled, have disabled items or disabled item hosts.
         $dbResult = DBSelect('SELECT t.triggerid' . ' FROM triggers t,functions f,items i,hosts h' . ' WHERE t.triggerid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=h.hostid' . ' AND (' . 'i.status=' . ITEM_STATUS_DISABLED . ' OR h.status=' . HOST_STATUS_NOT_MONITORED . ' OR t.status=' . TRIGGER_STATUS_DISABLED . ')' . ' AND ' . dbConditionInt('t.triggerid', $allUpTriggerIds));
         while ($row = DBfetch($dbResult)) {
             $resultTriggerId = $row['triggerid'];
             $disabledTriggerIds[$resultTriggerId] = $resultTriggerId;
         }
         // Now process all mapped dependencies and unset any disabled "up" triggers so they do not participate in
         // decisions regarding nesting resolution in next step.
         foreach ($downToUpTriggerIds as $downTriggerId => $upTriggerIds) {
             $upTriggerIdsToUnset = [];
             foreach ($upTriggerIds as $upTriggerId) {
                 if (isset($disabledTriggerIds[$upTriggerId])) {
                     unset($downToUpTriggerIds[$downTriggerId][$upTriggerId]);
                 }
             }
         }
         // Resolve dependencies for all result set triggers.
         foreach ($resultTriggerIds as $resultTriggerId) {
             // We start with result trigger.
             $triggerIds = [$resultTriggerId];
             // This also is unrolled recursive function and is repeated until there are no more trigger IDs to
             // check, add and resolve.
             do {
                 $nextTriggerIds = [];
                 foreach ($triggerIds as $triggerId) {
                     // Loop through all "up" triggers.
                     foreach ($downToUpTriggerIds[$triggerId] as $upTriggerId) {
                         if ($downToUpTriggerIds[$upTriggerId]) {
                             // If there this "up" trigger has "up" triggers of it's own, merge them and proceed with recursion.
                             $downToUpTriggerIds[$resultTriggerId] += $downToUpTriggerIds[$upTriggerId];
                             // Add trigger ID to be processed in next loop iteration.
                             $nextTriggerIds[] = $upTriggerId;
                         }
                     }
                 }
                 $triggerIds = $nextTriggerIds;
             } while ($triggerIds);
         }
         // Clean result set.
         foreach ($resultTriggerIds as $resultTriggerId) {
             foreach ($downToUpTriggerIds[$resultTriggerId] as $upTriggerId) {
                 // If "up" trigger is in problem state, dependent trigger should not be returned and is removed
                 // from results.
                 if ($upTriggerValues[$upTriggerId] == TRIGGER_VALUE_TRUE) {
                     unset($triggers[$resultTriggerId]);
                 }
             }
             // Check if result trigger is disabled and if so, remove from results.
             if (isset($disabledTriggerIds[$resultTriggerId])) {
                 unset($triggers[$resultTriggerId]);
             }
         }
     }
     // withLastEventUnacknowledged
     if (!is_null($options['withLastEventUnacknowledged'])) {
         $triggerIds = zbx_objectValues($triggers, 'triggerid');
         $eventIds = [];
         $eventsDb = DBselect('SELECT MAX(e.eventid) AS eventid,e.objectid' . ' FROM events e' . ' WHERE e.object=' . EVENT_OBJECT_TRIGGER . ' AND e.source=' . EVENT_SOURCE_TRIGGERS . ' AND ' . dbConditionInt('e.objectid', $triggerIds) . ' AND ' . dbConditionInt('e.value', [TRIGGER_VALUE_TRUE]) . ' GROUP BY e.objectid');
         while ($event = DBfetch($eventsDb)) {
             $eventIds[] = $event['eventid'];
         }
         $correctTriggerIds = DBfetchArrayAssoc(DBselect('SELECT e.objectid' . ' FROM events e ' . ' WHERE ' . dbConditionInt('e.eventid', $eventIds) . ' AND e.acknowledged=0'), 'objectid');
         foreach ($triggers as $triggerId => $trigger) {
             if (!isset($correctTriggerIds[$triggerId])) {
                 unset($triggers[$triggerId]);
             }
         }
     }
     return $triggers;
 }
コード例 #20
0
ファイル: tr_status.php プロジェクト: phedders/zabbix
    $triggers_num++;
    $row['events'] = array();
    $row['items'] = array();
    $triggers[$row['triggerid']] = $row;
    $triggerids[$row['triggerid']] = $row['triggerid'];
}
$sql = 'SELECT f.triggerid, i.* ' . ' FROM functions f, items i ' . ' WHERE ' . DBcondition('f.triggerid', $triggerids) . ' AND i.itemid=f.itemid';
$result = DBselect($sql);
while ($row = DBfetch($result)) {
    $item['itemid'] = $row['itemid'];
    $item['action'] = str_in_array($row['value_type'], array(ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_UINT64)) ? 'showgraph' : 'showvalues';
    $item['description'] = item_description($row);
    $triggers[$row['triggerid']]['items'][$row['itemid']] = $item;
}
$event_sql = 'SELECT e.eventid, e.value, e.clock, e.objectid as triggerid, e.acknowledged, t.type ' . ' FROM events e, triggers t ' . ' WHERE e.object=0 ' . ' AND ' . DBcondition('e.objectid', $triggerids) . ' AND t.triggerid=e.objectid ' . $event_cond . ' ORDER by e.object DESC, e.objectid DESC, e.eventid DESC';
$res_events = DBSelect($event_sql, $config['event_show_max'] * 100);
while ($row_event = DBfetch($res_events)) {
    if ($show_events == EVENTS_OPTION_NOFALSEFORB) {
        if (EVENTS_NOFALSEFORB_STATUS_FALSE == $show_events_status && $row_event['value'] != TRIGGER_VALUE_FALSE) {
            continue;
        }
        if (EVENTS_NOFALSEFORB_STATUS_TRUE == $show_events_status && $row_event['value'] != TRIGGER_VALUE_TRUE) {
            continue;
        }
        if ($row_event['value'] == TRIGGER_VALUE_FALSE && !event_initial_time($row_event)) {
            continue;
        }
    }
    $triggers[$row_event['triggerid']]['events'][$row_event['eventid']] = $row_event;
}
foreach ($triggers as $triggerid => $row) {
コード例 #21
0
ファイル: services.php プロジェクト: songyuanjie/zabbix-stats
check_fields($fields);
/* AJAX */
if (isset($_REQUEST['favobj'])) {
    if ('hat' == $_REQUEST['favobj']) {
        CProfile::update('web.services.hats.' . $_REQUEST['favref'] . '.state', $_REQUEST['state'], PROFILE_TYPE_INT);
    }
}
if (PAGE_TYPE_JS == $page['type'] || PAGE_TYPE_HTML_BLOCK == $page['type']) {
    include_once 'include/page_footer.php';
    exit;
}
//--------
//--------------------------------------------------------------------------
$available_triggers = get_accessible_triggers(PERM_READ_ONLY, array());
$sql = 'SELECT DISTINCT s.serviceid, sl.servicedownid, sl_p.serviceupid as serviceupid, s.triggerid, ' . ' s.name as caption, s.algorithm, t.description, t.expression, s.sortorder, sl.linkid, s.showsla, s.goodsla, s.status ' . ' FROM services s ' . ' LEFT JOIN triggers t ON s.triggerid = t.triggerid ' . ' LEFT JOIN services_links sl ON  s.serviceid = sl.serviceupid and NOT(sl.soft=0) ' . ' LEFT JOIN services_links sl_p ON  s.serviceid = sl_p.servicedownid and sl_p.soft=0 ' . ' WHERE ' . DBin_node('s.serviceid') . ' AND (t.triggerid IS NULL OR ' . DBcondition('t.triggerid', $available_triggers) . ') ' . ' ORDER BY s.sortorder, sl_p.serviceupid, s.serviceid';
$result = DBSelect($sql);
$services = array();
$row = array('id' => 0, 'serviceid' => 0, 'serviceupid' => 0, 'caption' => S_ROOT_SMALL, 'status' => SPACE, 'algorithm' => SPACE, 'description' => SPACE, 'soft' => 0, 'linkid' => '');
$services[0] = $row;
while ($row = DBFetch($result)) {
    $row['id'] = $row['serviceid'];
    empty($row['serviceupid']) ? $row['serviceupid'] = '0' : '';
    empty($row['triggerid']) ? $row['description'] = 'None' : ($row['description'] = expand_trigger_description($row['triggerid']));
    if (isset($services[$row['serviceid']])) {
        $services[$row['serviceid']] = zbx_array_merge($services[$row['serviceid']], $row);
    } else {
        $services[$row['serviceid']] = $row;
    }
    if (isset($row['serviceupid'])) {
        $services[$row['serviceupid']]['childs'][] = array('id' => $row['serviceid'], 'soft' => 0, 'linkid' => 0);
    }
コード例 #22
0
ファイル: services.inc.php プロジェクト: phedders/zabbix
function get_service_childs($serviceid, $soft = 0)
{
    $childs = array();
    $query = 'SELECT sl.servicedownid ' . ' FROM services_links sl ' . ' WHERE sl.serviceupid = ' . $serviceid . ($soft ? '' : ' AND sl.soft <> 1');
    $res = DBSelect($query);
    while ($row = DBFetch($res)) {
        $childs[] = $row['servicedownid'];
        $childs = array_merge($childs, get_service_childs($row['servicedownid']));
    }
    return $childs;
}
コード例 #23
0
    order_result($_REQUEST['steps'], 'no');
}
/*
 * Permissions
 */
if (isset($_REQUEST['httptestid'])) {
    $dbHttpTest = DBfetch(DBselect('SELECT wt.*,a.name AS application' . ' FROM httptest wt,applications a' . ' WHERE a.applicationid=wt.applicationid' . ' AND wt.httptestid=' . get_request('httptestid')));
    if (empty($dbHttpTest)) {
        access_deny();
    }
}
if (isset($_REQUEST['go'])) {
    if (!isset($_REQUEST['group_httptestid']) || !is_array($_REQUEST['group_httptestid'])) {
        access_deny();
    } else {
        $dbHttpTests = DBfetch(DBSelect('SELECT COUNT(*) AS cnt' . ' FROM httptest wt,applications a' . ' WHERE a.applicationid=wt.applicationid' . ' AND ' . dbConditionInt('wt.httptestid', $_REQUEST['group_httptestid'])));
        if ($dbHttpTests['cnt'] != count($_REQUEST['group_httptestid'])) {
            access_deny();
        }
    }
}
$_REQUEST['go'] = get_request('go', 'none');
/*
 * Filter
 */
$options = array('groups' => array('real_hosts' => true, 'not_proxy_hosts' => true, 'editable' => true), 'hosts' => array('editable' => true), 'hostid' => get_request('hostid', null), 'groupid' => get_request('groupid', null));
$pageFilter = new CPageFilter($options);
$_REQUEST['groupid'] = $pageFilter->groupid;
$_REQUEST['hostid'] = $pageFilter->hostid;
/*
 * Actions
コード例 #24
0
 /**
  * Unlinks the templates from the given hosts. If $tragetids is set to null, the templates will be unlinked from
  * all hosts.
  *
  * @param array      $templateids
  * @param null|array $targetids		the IDs of the hosts to unlink the templates from
  * @param bool       $clear			delete all of the inherited objects from the hosts
  */
 protected function unlink($templateids, $targetids = null, $clear = false)
 {
     $flags = $clear ? array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_RULE) : array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_RULE, ZBX_FLAG_DISCOVERY_PROTOTYPE);
     // check that all triggers on templates that we unlink, don't have items from another templates
     $sql = 'SELECT DISTINCT t.description' . ' FROM triggers t,functions f,items i' . ' WHERE t.triggerid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND ' . dbConditionInt('i.hostid', $templateids) . ' AND EXISTS (' . 'SELECT ff.triggerid' . ' FROM functions ff,items ii' . ' WHERE ff.itemid=ii.itemid' . ' AND ff.triggerid=t.triggerid' . ' AND ' . dbConditionInt('ii.hostid', $templateids, true) . ')' . ' AND t.flags=' . ZBX_FLAG_DISCOVERY_NORMAL;
     if ($dbTrigger = DBfetch(DBSelect($sql, 1))) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot unlink trigger "%s", it has items from template that is left linked to host.', $dbTrigger['description']));
     }
     $sqlFrom = ' triggers t,hosts h';
     $sqlWhere = ' EXISTS (' . 'SELECT ff.triggerid' . ' FROM functions ff,items ii' . ' WHERE ff.triggerid=t.templateid' . ' AND ii.itemid=ff.itemid' . ' AND ' . dbConditionInt('ii.hostid', $templateids) . ')' . ' AND ' . dbConditionInt('t.flags', $flags);
     if (!is_null($targetids)) {
         $sqlFrom = ' triggers t,functions f,items i,hosts h';
         $sqlWhere .= ' AND ' . dbConditionInt('i.hostid', $targetids) . ' AND f.itemid=i.itemid' . ' AND t.triggerid=f.triggerid' . ' AND h.hostid=i.hostid';
     }
     $sql = 'SELECT DISTINCT t.triggerid,t.description,t.flags,t.expression,h.name as host' . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere;
     $dbTriggers = DBSelect($sql);
     $triggers = array(ZBX_FLAG_DISCOVERY_NORMAL => array(), ZBX_FLAG_DISCOVERY_PROTOTYPE => array());
     $triggerids = array();
     while ($trigger = DBfetch($dbTriggers)) {
         $triggers[$trigger['flags']][$trigger['triggerid']] = array('description' => $trigger['description'], 'expression' => explode_exp($trigger['expression']), 'triggerid' => $trigger['triggerid'], 'host' => $trigger['host']);
         if (!in_array($trigger['triggerid'], $triggerids)) {
             array_push($triggerids, $trigger['triggerid']);
         }
     }
     if (!empty($triggers[ZBX_FLAG_DISCOVERY_NORMAL])) {
         if ($clear) {
             $result = API::Trigger()->delete(array_keys($triggers[ZBX_FLAG_DISCOVERY_NORMAL]), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear triggers'));
             }
         } else {
             DB::update('triggers', array('values' => array('templateid' => 0), 'where' => array('triggerid' => array_keys($triggers[ZBX_FLAG_DISCOVERY_NORMAL]))));
             foreach ($triggers[ZBX_FLAG_DISCOVERY_NORMAL] as $trigger) {
                 info(_s('Unlinked: Trigger "%1$s" on "%2$s".', $trigger['description'], $trigger['host']));
             }
         }
     }
     if (!empty($triggers[ZBX_FLAG_DISCOVERY_PROTOTYPE])) {
         if ($clear) {
             $result = API::TriggerPrototype()->delete(array_keys($triggers[ZBX_FLAG_DISCOVERY_PROTOTYPE]), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear triggers'));
             }
         } else {
             DB::update('triggers', array('values' => array('templateid' => 0), 'where' => array('triggerid' => array_keys($triggers[ZBX_FLAG_DISCOVERY_PROTOTYPE]))));
             foreach ($triggers[ZBX_FLAG_DISCOVERY_PROTOTYPE] as $trigger) {
                 info(_s('Unlinked: Trigger prototype "%1$s" on "%2$s".', $trigger['description'], $trigger['host']));
             }
         }
     }
     /* ITEMS, DISCOVERY RULES {{{ */
     $sqlFrom = ' items i1,items i2,hosts h';
     $sqlWhere = ' i2.itemid=i1.templateid' . ' AND ' . dbConditionInt('i2.hostid', $templateids) . ' AND ' . dbConditionInt('i1.flags', $flags) . ' AND h.hostid=i1.hostid';
     if (!is_null($targetids)) {
         $sqlWhere .= ' AND ' . dbConditionInt('i1.hostid', $targetids);
     }
     $sql = 'SELECT DISTINCT i1.itemid,i1.flags,i1.name,i1.hostid,h.name as host' . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere;
     $dbItems = DBSelect($sql);
     $items = array(ZBX_FLAG_DISCOVERY_NORMAL => array(), ZBX_FLAG_DISCOVERY_RULE => array(), ZBX_FLAG_DISCOVERY_PROTOTYPE => array());
     while ($item = DBfetch($dbItems)) {
         $items[$item['flags']][$item['itemid']] = array('name' => $item['name'], 'host' => $item['host']);
     }
     if (!empty($items[ZBX_FLAG_DISCOVERY_RULE])) {
         if ($clear) {
             $result = API::DiscoveryRule()->delete(array_keys($items[ZBX_FLAG_DISCOVERY_RULE]), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear discovery rules'));
             }
         } else {
             DB::update('items', array('values' => array('templateid' => 0), 'where' => array('itemid' => array_keys($items[ZBX_FLAG_DISCOVERY_RULE]))));
             foreach ($items[ZBX_FLAG_DISCOVERY_RULE] as $discoveryRule) {
                 info(_s('Unlinked: Discovery rule "%1$s" on "%2$s".', $discoveryRule['name'], $discoveryRule['host']));
             }
         }
     }
     if (!empty($items[ZBX_FLAG_DISCOVERY_NORMAL])) {
         if ($clear) {
             $result = API::Item()->delete(array_keys($items[ZBX_FLAG_DISCOVERY_NORMAL]), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear items'));
             }
         } else {
             DB::update('items', array('values' => array('templateid' => 0), 'where' => array('itemid' => array_keys($items[ZBX_FLAG_DISCOVERY_NORMAL]))));
             foreach ($items[ZBX_FLAG_DISCOVERY_NORMAL] as $item) {
                 info(_s('Unlinked: Item "%1$s" on "%2$s".', $item['name'], $item['host']));
             }
         }
     }
     if (!empty($items[ZBX_FLAG_DISCOVERY_PROTOTYPE])) {
         if ($clear) {
             $result = API::Itemprototype()->delete(array_keys($items[ZBX_FLAG_DISCOVERY_PROTOTYPE]), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear item prototypes'));
             }
         } else {
             DB::update('items', array('values' => array('templateid' => 0), 'where' => array('itemid' => array_keys($items[ZBX_FLAG_DISCOVERY_PROTOTYPE]))));
             foreach ($items[ZBX_FLAG_DISCOVERY_PROTOTYPE] as $item) {
                 info(_s('Unlinked: Item prototype "%1$s" on "%2$s".', $item['name'], $item['host']));
             }
         }
     }
     /* }}} ITEMS, DISCOVERY RULES */
     // host prototypes
     // we need only to unlink host prototypes. in case of unlink and clear they will be deleted together with LLD rules.
     if (!$clear && isset($items[ZBX_FLAG_DISCOVERY_RULE])) {
         $discoveryRuleIds = array_keys($items[ZBX_FLAG_DISCOVERY_RULE]);
         $hostPrototypes = DBfetchArrayAssoc(DBSelect('SELECT DISTINCT h.hostid,h.host,h3.host AS parent_host' . ' FROM hosts h' . ' INNER JOIN host_discovery hd ON h.hostid=hd.hostid' . ' INNER JOIN hosts h2 ON h.templateid=h2.hostid' . ' INNER JOIN host_discovery hd2 ON h.hostid=hd.hostid' . ' INNER JOIN items i ON hd.parent_itemid=i.itemid' . ' INNER JOIN hosts h3 ON i.hostid=h3.hostid' . ' WHERE ' . dbConditionInt('hd.parent_itemid', $discoveryRuleIds)), 'hostid');
         if ($hostPrototypes) {
             DB::update('hosts', array('values' => array('templateid' => 0), 'where' => array('hostid' => array_keys($hostPrototypes))));
             DB::update('group_prototype', array('values' => array('templateid' => 0), 'where' => array('hostid' => array_keys($hostPrototypes))));
             foreach ($hostPrototypes as $hostPrototype) {
                 info(_s('Unlinked: Host prototype "%1$s" on "%2$s".', $hostPrototype['host'], $hostPrototype['parent_host']));
             }
         }
     }
     /* GRAPHS {{{ */
     $sqlFrom = ' graphs g,hosts h';
     $sqlWhere = ' EXISTS (' . 'SELECT ggi.graphid' . ' FROM graphs_items ggi,items ii' . ' WHERE ggi.graphid=g.templateid' . ' AND ii.itemid=ggi.itemid' . ' AND ' . dbConditionInt('ii.hostid', $templateids) . ')' . ' AND ' . dbConditionInt('g.flags', $flags);
     if (!is_null($targetids)) {
         $sqlFrom = ' graphs g,graphs_items gi,items i,hosts h';
         $sqlWhere .= ' AND ' . dbConditionInt('i.hostid', $targetids) . ' AND gi.itemid=i.itemid' . ' AND g.graphid=gi.graphid' . ' AND h.hostid=i.hostid';
     }
     $sql = 'SELECT DISTINCT g.graphid,g.name,g.flags,h.name as host' . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere;
     $dbGraphs = DBSelect($sql);
     $graphs = array(ZBX_FLAG_DISCOVERY_NORMAL => array(), ZBX_FLAG_DISCOVERY_PROTOTYPE => array());
     while ($graph = DBfetch($dbGraphs)) {
         $graphs[$graph['flags']][$graph['graphid']] = array('name' => $graph['name'], 'graphid' => $graph['graphid'], 'host' => $graph['host']);
     }
     if (!empty($graphs[ZBX_FLAG_DISCOVERY_PROTOTYPE])) {
         if ($clear) {
             $result = API::GraphPrototype()->delete(array_keys($graphs[ZBX_FLAG_DISCOVERY_PROTOTYPE]), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear graph prototypes'));
             }
         } else {
             DB::update('graphs', array('values' => array('templateid' => 0), 'where' => array('graphid' => array_keys($graphs[ZBX_FLAG_DISCOVERY_PROTOTYPE]))));
             foreach ($graphs[ZBX_FLAG_DISCOVERY_PROTOTYPE] as $graph) {
                 info(_s('Unlinked: Graph prototype "%1$s" on "%2$s".', $graph['name'], $graph['host']));
             }
         }
     }
     if (!empty($graphs[ZBX_FLAG_DISCOVERY_NORMAL])) {
         if ($clear) {
             $result = API::Graph()->delete(array_keys($graphs[ZBX_FLAG_DISCOVERY_NORMAL]), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear graphs.'));
             }
         } else {
             DB::update('graphs', array('values' => array('templateid' => 0), 'where' => array('graphid' => array_keys($graphs[ZBX_FLAG_DISCOVERY_NORMAL]))));
             foreach ($graphs[ZBX_FLAG_DISCOVERY_NORMAL] as $graph) {
                 info(_s('Unlinked: Graph "%1$s" on "%2$s".', $graph['name'], $graph['host']));
             }
         }
     }
     /* }}} GRAPHS */
     // http tests
     $sqlWhere = '';
     if (!is_null($targetids)) {
         $sqlWhere = ' AND ' . dbConditionInt('ht1.hostid', $targetids);
     }
     $sql = 'SELECT DISTINCT ht1.httptestid,ht1.name,h.name as host' . ' FROM httptest ht1' . ' INNER JOIN httptest ht2 ON ht2.httptestid=ht1.templateid' . ' INNER JOIN hosts h ON h.hostid=ht1.hostid' . ' WHERE ' . dbConditionInt('ht2.hostid', $templateids) . $sqlWhere;
     $dbHttpTests = DBSelect($sql);
     $httpTests = array();
     while ($httpTest = DBfetch($dbHttpTests)) {
         $httpTests[$httpTest['httptestid']] = array('name' => $httpTest['name'], 'host' => $httpTest['host']);
     }
     if (!empty($httpTests)) {
         if ($clear) {
             $result = API::HttpTest()->delete(array_keys($httpTests), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear Web scenarios.'));
             }
         } else {
             DB::update('httptest', array('values' => array('templateid' => 0), 'where' => array('httptestid' => array_keys($httpTests))));
             foreach ($httpTests as $httpTest) {
                 info(_s('Unlinked: Web scenario "%1$s" on "%2$s".', $httpTest['name'], $httpTest['host']));
             }
         }
     }
     /* APPLICATIONS {{{ */
     $sql = 'SELECT at.application_templateid,at.applicationid,h.name,h.host,h.hostid' . ' FROM applications a1,application_template at,applications a2,hosts h' . ' WHERE a1.applicationid=at.applicationid' . ' AND at.templateid=a2.applicationid' . ' AND ' . dbConditionInt('a2.hostid', $templateids) . ' AND a1.hostid=h.hostid';
     if ($targetids) {
         $sql .= ' AND ' . dbConditionInt('a1.hostid', $targetids);
     }
     $query = DBselect($sql);
     $applicationTemplates = array();
     while ($applicationTemplate = DBfetch($query)) {
         $applicationTemplates[] = array('applicationid' => $applicationTemplate['applicationid'], 'application_templateid' => $applicationTemplate['application_templateid'], 'name' => $applicationTemplate['name'], 'hostid' => $applicationTemplate['hostid'], 'host' => $applicationTemplate['host']);
     }
     if ($applicationTemplates) {
         // unlink applications from templates
         DB::delete('application_template', array('application_templateid' => zbx_objectValues($applicationTemplates, 'application_templateid')));
         if ($clear) {
             // delete inherited applications that are no longer linked to any templates
             $applications = DBfetchArray(DBselect('SELECT a.applicationid' . ' FROM applications a' . ' LEFT JOIN application_template at ON a.applicationid=at.applicationid ' . ' WHERE ' . dbConditionInt('a.applicationid', zbx_objectValues($applicationTemplates, 'applicationid')) . ' AND at.applicationid IS NULL'));
             $result = API::Application()->delete(zbx_objectValues($applications, 'applicationid'), true);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_INTERNAL, _('Cannot unlink and clear applications.'));
             }
         } else {
             foreach ($applicationTemplates as $application) {
                 info(_s('Unlinked: Application "%1$s" on "%2$s".', $application['name'], $application['host']));
             }
         }
     }
     /* }}} APPLICATIONS */
     parent::unlink($templateids, $targetids);
 }
コード例 #25
0
ファイル: adm.regexps.php プロジェクト: jbfavre/debian-zabbix
        }
        unset($_REQUEST['form'], $_REQUEST['regexpid']);
    }
    $result = DBend($result);
    if ($result) {
        uncheckTableRows();
    }
    show_messages($result, _n('Regular expression deleted', 'Regular expressions deleted', $regExpCount), _n('Cannot delete regular expression', 'Cannot delete regular expressions', $regExpCount));
}
/*
 * Display
 */
if (isset($_REQUEST['form'])) {
    $data = ['form_refresh' => getRequest('form_refresh'), 'regexpid' => getRequest('regexpid')];
    if (isset($_REQUEST['regexpid']) && !isset($_REQUEST['form_refresh'])) {
        $regExp = DBfetch(DBSelect('SELECT re.name,re.test_string' . ' FROM regexps re' . ' WHERE re.regexpid=' . zbx_dbstr($_REQUEST['regexpid'])));
        $data['name'] = $regExp['name'];
        $data['test_string'] = $regExp['test_string'];
        $data['expressions'] = DBfetchArray(DBselect('SELECT e.expressionid,e.expression,e.expression_type,e.exp_delimiter,e.case_sensitive' . ' FROM expressions e' . ' WHERE e.regexpid=' . zbx_dbstr($_REQUEST['regexpid']) . ' ORDER BY e.expression_type'));
    } else {
        $data['name'] = getRequest('name', '');
        $data['test_string'] = getRequest('test_string', '');
        $data['expressions'] = getRequest('expressions', [['expression' => '', 'expression_type' => EXPRESSION_TYPE_INCLUDED, 'exp_delimiter' => ',', 'case_sensitive' => 0]]);
    }
    $view = new CView('administration.general.regularexpressions.edit', $data);
} else {
    $data = ['regexps' => [], 'regexpids' => []];
    $dbRegExp = DBselect('SELECT re.* FROM regexps re');
    while ($regExp = DBfetch($dbRegExp)) {
        $regExp['expressions'] = [];
        $data['regexps'][$regExp['regexpid']] = $regExp;
コード例 #26
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     $maintenanceIds = array_keys($result);
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     // selectGroups
     if (is_array($options['selectGroups']) || str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) {
         $objParams = array('output' => $options['selectGroups'], 'maintenanceids' => $maintenanceIds, 'preservekeys' => true);
         $groups = API::HostGroup()->get($objParams);
         foreach ($groups as $group) {
             $gmaintenances = $group['maintenances'];
             unset($group['maintenances']);
             foreach ($gmaintenances as $maintenance) {
                 $result[$maintenance['maintenanceid']]['groups'][] = $group;
             }
         }
     }
     // selectHosts
     if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
         $objParams = array('output' => $options['selectHosts'], 'maintenanceids' => $maintenanceIds, 'preservekeys' => true);
         $hosts = API::Host()->get($objParams);
         foreach ($hosts as $host) {
             $hmaintenances = $host['maintenances'];
             unset($host['maintenances']);
             foreach ($hmaintenances as $maintenance) {
                 $result[$maintenance['maintenanceid']]['hosts'][] = $host;
             }
         }
     }
     // selectTimeperiods
     if ($options['selectTimeperiods'] !== null) {
         foreach ($result as &$maintenance) {
             $maintenance['timeperiods'] = array();
         }
         unset($maintenance);
         // create the SELECT part of the query
         $sqlParts = $this->applyQueryOutputOptions('timeperiods', 'tp', array('output' => $options['selectTimeperiods']), array('select' => array('tp.timeperiodid')));
         $query = DBSelect('SELECT ' . implode($sqlParts['select'], ',') . ',mw.maintenanceid' . ' FROM timeperiods tp,maintenances_windows mw' . ' WHERE ' . dbConditionInt('mw.maintenanceid', $maintenanceIds) . ' AND tp.timeperiodid=mw.timeperiodid');
         while ($tp = DBfetch($query)) {
             $refId = $tp['maintenanceid'];
             $tp = $this->unsetExtraFields('timeperiods', $tp, $options['selectTimeperiods']);
             $result[$refId]['timeperiods'][] = $tp;
         }
     }
     return $result;
 }
コード例 #27
0
ファイル: CApiService.php プロジェクト: jbfavre/debian-zabbix
 /**
  * Constructs an SQL SELECT query for a specific table from the given API options, executes it and returns
  * the result.
  *
  * TODO: add global 'countOutput' support
  *
  * @param string $tableName
  * @param array  $options
  *
  * @return array
  */
 protected function select($tableName, array $options)
 {
     $limit = isset($options['limit']) ? $options['limit'] : null;
     $sql = $this->createSelectQuery($tableName, $options);
     $objects = DBfetchArray(DBSelect($sql, $limit));
     if (isset($options['preservekeys'])) {
         $rs = [];
         foreach ($objects as $object) {
             $rs[$object[$this->pk($tableName)]] = $object;
         }
         return $rs;
     } else {
         return $objects;
     }
 }
コード例 #28
0
ファイル: CHostBase.php プロジェクト: jbfavre/debian-zabbix
 /**
  * Links the templates to the given hosts.
  *
  * @param array $templateIds
  * @param array $targetIds		an array of host IDs to link the templates to
  *
  * @return array 	an array of added hosts_templates rows, with 'hostid' and 'templateid' set for each row
  */
 protected function link(array $templateIds, array $targetIds)
 {
     if (empty($templateIds)) {
         return;
     }
     // permission check
     if (!API::Template()->isReadable($templateIds)) {
         self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!'));
     }
     // check if someone passed duplicate templates in the same query
     $templateIdDuplicates = zbx_arrayFindDuplicates($templateIds);
     if (!zbx_empty($templateIdDuplicates)) {
         $duplicatesFound = [];
         foreach ($templateIdDuplicates as $value => $count) {
             $duplicatesFound[] = _s('template ID "%1$s" is passed %2$s times', $value, $count);
         }
         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot pass duplicate template IDs for the linkage: %s.', implode(', ', $duplicatesFound)));
     }
     // get DB templates which exists in all targets
     $res = DBselect('SELECT * FROM hosts_templates WHERE ' . dbConditionInt('hostid', $targetIds));
     $mas = [];
     while ($row = DBfetch($res)) {
         if (!isset($mas[$row['templateid']])) {
             $mas[$row['templateid']] = [];
         }
         $mas[$row['templateid']][$row['hostid']] = 1;
     }
     $targetIdCount = count($targetIds);
     $commonDBTemplateIds = [];
     foreach ($mas as $templateId => $targetList) {
         if (count($targetList) == $targetIdCount) {
             $commonDBTemplateIds[] = $templateId;
         }
     }
     // check if there are any template with triggers which depends on triggers in templates which will be not linked
     $commonTemplateIds = array_unique(array_merge($commonDBTemplateIds, $templateIds));
     foreach ($templateIds as $templateid) {
         $triggerids = [];
         $dbTriggers = get_triggers_by_hostid($templateid);
         while ($trigger = DBfetch($dbTriggers)) {
             $triggerids[$trigger['triggerid']] = $trigger['triggerid'];
         }
         $sql = 'SELECT DISTINCT h.host' . ' FROM trigger_depends td,functions f,items i,hosts h' . ' WHERE (' . dbConditionInt('td.triggerid_down', $triggerids) . ' AND f.triggerid=td.triggerid_up' . ' )' . ' AND i.itemid=f.itemid' . ' AND h.hostid=i.hostid' . ' AND ' . dbConditionInt('h.hostid', $commonTemplateIds, true) . ' AND h.status=' . HOST_STATUS_TEMPLATE;
         if ($dbDepHost = DBfetch(DBselect($sql))) {
             $tmpTpls = API::Template()->get(['templateids' => $templateid, 'output' => API_OUTPUT_EXTEND]);
             $tmpTpl = reset($tmpTpls);
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Trigger in template "%1$s" has dependency with trigger in template "%2$s".', $tmpTpl['host'], $dbDepHost['host']));
         }
     }
     $res = DBselect('SELECT ht.hostid,ht.templateid' . ' FROM hosts_templates ht' . ' WHERE ' . dbConditionInt('ht.hostid', $targetIds) . ' AND ' . dbConditionInt('ht.templateid', $templateIds));
     $linked = [];
     while ($row = DBfetch($res)) {
         if (!isset($linked[$row['hostid']])) {
             $linked[$row['hostid']] = [];
         }
         $linked[$row['hostid']][$row['templateid']] = 1;
     }
     // add template linkages, if problems rollback later
     $hostsLinkageInserts = [];
     foreach ($targetIds as $targetid) {
         foreach ($templateIds as $templateid) {
             if (isset($linked[$targetid]) && isset($linked[$targetid][$templateid])) {
                 continue;
             }
             $hostsLinkageInserts[] = ['hostid' => $targetid, 'templateid' => $templateid];
         }
     }
     DB::insert('hosts_templates', $hostsLinkageInserts);
     // check if all trigger templates are linked to host.
     // we try to find template that is not linked to hosts ($targetids)
     // and exists trigger which reference that template and template from ($templateids)
     $sql = 'SELECT DISTINCT h.host' . ' FROM functions f,items i,triggers t,hosts h' . ' WHERE f.itemid=i.itemid' . ' AND f.triggerid=t.triggerid' . ' AND i.hostid=h.hostid' . ' AND h.status=' . HOST_STATUS_TEMPLATE . ' AND NOT EXISTS (SELECT 1 FROM hosts_templates ht WHERE ht.templateid=i.hostid AND ' . dbConditionInt('ht.hostid', $targetIds) . ')' . ' AND EXISTS (SELECT 1 FROM functions ff,items ii WHERE ff.itemid=ii.itemid AND ff.triggerid=t.triggerid AND ' . dbConditionInt('ii.hostid', $templateIds) . ')';
     if ($dbNotLinkedTpl = DBfetch(DBSelect($sql, 1))) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Trigger has items from template "%1$s" that is not linked to host.', $dbNotLinkedTpl['host']));
     }
     // check template linkage circularity
     $res = DBselect('SELECT ht.hostid,ht.templateid' . ' FROM hosts_templates ht,hosts h' . ' WHERE ht.hostid=h.hostid ' . ' AND h.status IN(' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')');
     // build linkage graph and prepare list for $rootList generation
     $graph = [];
     $hasParentList = [];
     $hasChildList = [];
     $all = [];
     while ($row = DBfetch($res)) {
         if (!isset($graph[$row['hostid']])) {
             $graph[$row['hostid']] = [];
         }
         $graph[$row['hostid']][] = $row['templateid'];
         $hasParentList[$row['templateid']] = $row['templateid'];
         $hasChildList[$row['hostid']] = $row['hostid'];
         $all[$row['templateid']] = $row['templateid'];
         $all[$row['hostid']] = $row['hostid'];
     }
     // get list of templates without parents
     $rootList = [];
     foreach ($hasChildList as $parentId) {
         if (!isset($hasParentList[$parentId])) {
             $rootList[] = $parentId;
         }
     }
     // search cycles and double linkages in rooted parts of graph
     $visited = [];
     foreach ($rootList as $root) {
         $path = [];
         // raise exception on cycle or double linkage
         $this->checkCircularAndDoubleLinkage($graph, $root, $path, $visited);
     }
     // there is still possible cycles without root
     if (count($visited) < count($all)) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Circular template linkage is not allowed.'));
     }
     return $hostsLinkageInserts;
 }
コード例 #29
0
ファイル: services.php プロジェクト: phedders/zabbix
$fields = array("msg" => array(T_ZBX_STR, O_OPT, null, null, NULL), 'favobj' => array(T_ZBX_STR, O_OPT, P_ACT, IN("'hat'"), NULL), 'favid' => array(T_ZBX_STR, O_OPT, P_ACT, NOT_EMPTY, 'isset({favobj})'), 'state' => array(T_ZBX_INT, O_OPT, P_ACT, NOT_EMPTY, 'isset({favobj})'));
check_fields($fields);
/* AJAX */
if (isset($_REQUEST['favobj'])) {
    if ('hat' == $_REQUEST['favobj']) {
        update_profile('web.services.hats.' . $_REQUEST['favid'] . '.state', $_REQUEST['state'], PROFILE_TYPE_INT);
    }
}
if (PAGE_TYPE_JS == $page['type'] || PAGE_TYPE_HTML_BLOCK == $page['type']) {
    exit;
}
//--------
//--------------------------------------------------------------------------
$available_triggers = get_accessible_triggers(PERM_READ_ONLY, array(), PERM_RES_IDS_ARRAY);
$query = 'SELECT DISTINCT s.serviceid, sl.servicedownid, sl_p.serviceupid as serviceupid, s.triggerid, ' . ' s.name as caption, s.algorithm, t.description, t.expression, s.sortorder, sl.linkid, s.showsla, s.goodsla, s.status ' . ' FROM services s ' . ' LEFT JOIN triggers t ON s.triggerid = t.triggerid ' . ' LEFT JOIN services_links sl ON  s.serviceid = sl.serviceupid and NOT(sl.soft=0) ' . ' LEFT JOIN services_links sl_p ON  s.serviceid = sl_p.servicedownid and sl_p.soft=0 ' . ' WHERE ' . DBin_node('s.serviceid') . ' AND (t.triggerid IS NULL OR ' . DBcondition('t.triggerid', $available_triggers) . ') ' . ' ORDER BY s.sortorder, sl_p.serviceupid, s.serviceid';
$result = DBSelect($query);
$services = array();
$row = array('id' => 0, 'serviceid' => 0, 'serviceupid' => 0, 'caption' => S_ROOT_SMALL, 'status' => SPACE, 'algorithm' => SPACE, 'description' => SPACE, 'soft' => 0, 'linkid' => '');
$services[0] = $row;
while ($row = DBFetch($result)) {
    $row['id'] = $row['serviceid'];
    empty($row['serviceupid']) ? $row['serviceupid'] = '0' : '';
    empty($row['triggerid']) ? $row['description'] = 'None' : ($row['description'] = expand_trigger_description($row['triggerid']));
    if (isset($services[$row['serviceid']])) {
        $services[$row['serviceid']] = array_merge($services[$row['serviceid']], $row);
    } else {
        $services[$row['serviceid']] = $row;
    }
    if (isset($row['serviceupid'])) {
        $services[$row['serviceupid']]['childs'][] = array('id' => $row['serviceid'], 'soft' => 0, 'linkid' => 0);
    }
コード例 #30
0
ファイル: profiles.inc.php プロジェクト: hujingguang/work
function add_user_history($page)
{
    $userid = CWebUser::$data['userid'];
    $title = $page['title'];
    if (isset($page['hist_arg']) && is_array($page['hist_arg'])) {
        $url = '';
        foreach ($page['hist_arg'] as $arg) {
            if (isset($_REQUEST[$arg])) {
                $url .= url_param($arg, true);
            }
        }
        if (!empty($url)) {
            $url[0] = '?';
        }
        $url = $page['file'] . $url;
    } else {
        $url = $page['file'];
    }
    // if url length is greater than db field size, skip history update
    $historyTableSchema = DB::getSchema('user_history');
    if (zbx_strlen($url) > $historyTableSchema['fields']['url5']['length']) {
        return false;
    }
    $history5 = DBfetch(DBSelect('SELECT uh.title5,uh.url5' . ' FROM user_history uh' . ' WHERE uh.userid=' . $userid));
    if ($history5 && $history5['title5'] == $title) {
        if ($history5['url5'] != $url) {
            // title same, url isnt, change only url
            $sql = 'UPDATE user_history' . ' SET url5=' . zbx_dbstr($url) . ' WHERE userid=' . $userid;
        } else {
            // no need to change anything;
            return null;
        }
    } else {
        // new page with new title is added
        if ($history5 === false) {
            $userhistoryid = get_dbid('user_history', 'userhistoryid');
            $sql = 'INSERT INTO user_history (userhistoryid, userid, title5, url5)' . ' VALUES(' . $userhistoryid . ', ' . $userid . ', ' . zbx_dbstr($title) . ', ' . zbx_dbstr($url) . ')';
        } else {
            $sql = 'UPDATE user_history' . ' SET title1=title2,' . ' url1=url2,' . ' title2=title3,' . ' url2=url3,' . ' title3=title4,' . ' url3=url4,' . ' title4=title5,' . ' url4=url5,' . ' title5=' . zbx_dbstr($title) . ',' . ' url5=' . zbx_dbstr($url) . ' WHERE userid=' . $userid;
        }
    }
    return DBexecute($sql);
}