public function bodyToString()
 {
     $this->cleanItems();
     $total = 0;
     // fetch accessible host ids
     $hosts = API::Host()->get(array('nodeids' => get_current_nodeid(true), 'output' => array('hostid'), 'preservekeys' => true));
     $hostIds = array_keys($hosts);
     if (remove_nodes_from_id($this->groupid) > 0) {
         $cond_from = ',hosts_groups hg';
         $cond_where = ' AND hg.hostid=h.hostid AND hg.groupid=' . zbx_dbstr($this->groupid);
     } else {
         $cond_from = '';
         $cond_where = andDbNode('h.hostid', $this->nodeid);
     }
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_TRUE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $avail = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_FALSE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $notav = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_UNKNOWN . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $uncn = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $node = get_node_by_nodeid($this->nodeid);
     $header_str = _('Hosts info') . SPACE;
     if ($node > 0) {
         $header_str .= '(' . $node['name'] . ')' . SPACE;
     }
     if (remove_nodes_from_id($this->groupid) > 0) {
         $group = get_hostgroup_by_groupid($this->groupid);
         $header_str .= _('Group') . SPACE . '"' . $group['name'] . '"';
     } else {
         $header_str .= _('All groups');
     }
     $header = new CCol($header_str, 'header');
     if ($this->style == STYLE_HORISONTAL) {
         $header->setColspan(4);
     }
     $this->addRow($header);
     $avail = new CCol($avail . '  ' . _('Available'), 'avail');
     $notav = new CCol($notav . '  ' . _('Not available'), 'notav');
     $uncn = new CCol($uncn . '  ' . _('Unknown'), 'uncn');
     $total = new CCol($total . '  ' . _('Total'), 'total');
     if ($this->style == STYLE_HORISONTAL) {
         $this->addRow(array($avail, $notav, $uncn, $total));
     } else {
         $this->addRow($avail);
         $this->addRow($notav);
         $this->addRow($uncn);
         $this->addRow($total);
     }
     return parent::bodyToString();
 }
Beispiel #2
0
 public static function login($login, $password)
 {
     try {
         self::setDefault();
         self::$data = API::User()->login(array('user' => $login, 'password' => $password, 'userData' => true));
         if (!self::$data) {
             throw new Exception();
         }
         if (self::$data['gui_access'] == GROUP_GUI_ACCESS_DISABLED) {
             error(_('GUI access disabled.'));
             throw new Exception();
         }
         if (empty(self::$data['url'])) {
             self::$data['url'] = CProfile::get('web.menu.view.last', 'index.php');
         }
         if (isset(self::$data['attempt_failed']) && self::$data['attempt_failed']) {
             CProfile::init();
             CProfile::update('web.login.attempt.failed', self::$data['attempt_failed'], PROFILE_TYPE_INT);
             CProfile::update('web.login.attempt.ip', self::$data['attempt_ip'], PROFILE_TYPE_STR);
             CProfile::update('web.login.attempt.clock', self::$data['attempt_clock'], PROFILE_TYPE_INT);
             CProfile::flush();
         }
         // remove guest session after successful login
         DBexecute('DELETE FROM sessions WHERE sessionid=' . zbx_dbstr(get_cookie('zbx_sessionid')));
         zbx_setcookie('zbx_sessionid', self::$data['sessionid'], self::$data['autologin'] ? time() + SEC_PER_DAY * 31 : 0);
         return true;
     } catch (Exception $e) {
         self::setDefault();
         return false;
     }
 }
 /**
  * Import template screens.
  *
  * @param array $allScreens
  *
  * @return void
  */
 public function import(array $allScreens)
 {
     $screensToCreate = array();
     $screensToUpdate = array();
     foreach ($allScreens as $template => $screens) {
         // TODO: select all at once out of loop
         $dbScreens = DBselect('SELECT s.screenid,s.name FROM screens s WHERE' . ' s.templateid=' . zbx_dbstr($this->referencer->resolveTemplate($template)) . ' AND ' . dbConditionString('s.name', array_keys($screens)));
         while ($dbScreen = DBfetch($dbScreens)) {
             $screens[$dbScreen['name']]['screenid'] = $dbScreen['screenid'];
         }
         foreach ($screens as $screen) {
             $screen = $this->resolveScreenReferences($screen);
             if (isset($screen['screenid'])) {
                 $screensToUpdate[] = $screen;
             } else {
                 $screen['templateid'] = $this->referencer->resolveTemplate($template);
                 $screensToCreate[] = $screen;
             }
         }
     }
     if ($this->options['templateScreens']['createMissing'] && $screensToCreate) {
         API::TemplateScreen()->create($screensToCreate);
     }
     if ($this->options['templateScreens']['updateExisting'] && $screensToUpdate) {
         API::TemplateScreen()->update($screensToUpdate);
     }
 }
 /**
  * Add trigger by trigger id, required fields for description expanding are queried from DB.
  *
  * @param string $triggerId
  *
  * @return string
  */
 public function expandById($triggerId)
 {
     $trigger = DBfetch(DBselect('SELECT DISTINCT t.description,t.expression,t.triggerid' . ' FROM triggers t' . ' WHERE t.triggerid=' . zbx_dbstr($triggerId)));
     $triggers = $this->expandDescriptions(array($trigger['triggerid'] => $trigger));
     $trigger = reset($triggers);
     return $trigger['description'];
 }
Beispiel #5
0
function updateRegexp(array $regexp, array $expressions)
{
    try {
        $regexpId = $regexp['regexpid'];
        unset($regexp['regexpid']);
        // check existence
        if (!getRegexp($regexpId)) {
            throw new Exception(_('Regular expression does not exist.'));
        }
        // check required fields
        $dbFields = array('name' => null);
        if (!check_db_fields($dbFields, $regexp)) {
            throw new Exception(_('Incorrect arguments passed to function') . ' [updateRegexp]');
        }
        // check duplicate name
        $dbRegexp = DBfetch(DBselect('SELECT re.regexpid' . ' FROM regexps re' . ' WHERE re.name=' . zbx_dbstr($regexp['name']) . andDbNode('re.regexpid')));
        if ($dbRegexp && bccomp($regexpId, $dbRegexp['regexpid']) != 0) {
            throw new Exception(_s('Regular expression "%s" already exists.', $regexp['name']));
        }
        rewriteRegexpExpressions($regexpId, $expressions);
        DB::update('regexps', array('values' => $regexp, 'where' => array('regexpid' => $regexpId)));
    } catch (Exception $e) {
        error($e->getMessage());
        return false;
    }
    return true;
}
Beispiel #6
0
 /**
  * Tries to login a user and populates self::$data on success.
  *
  * @param string $login			user login
  * @param string $password		user password
  *
  * @throws Exception if user cannot be logged in
  *
  * @return bool
  */
 public static function login($login, $password)
 {
     try {
         self::setDefault();
         self::$data = API::User()->login(array('user' => $login, 'password' => $password, 'userData' => true));
         if (!self::$data) {
             throw new Exception();
         }
         if (self::$data['gui_access'] == GROUP_GUI_ACCESS_DISABLED) {
             error(_('GUI access disabled.'));
             throw new Exception();
         }
         if (empty(self::$data['url'])) {
             self::$data['url'] = CProfile::get('web.menu.view.last', 'index.php');
         }
         $result = (bool) self::$data;
         if (isset(self::$data['attempt_failed']) && self::$data['attempt_failed']) {
             CProfile::init();
             CProfile::update('web.login.attempt.failed', self::$data['attempt_failed'], PROFILE_TYPE_INT);
             CProfile::update('web.login.attempt.ip', self::$data['attempt_ip'], PROFILE_TYPE_STR);
             CProfile::update('web.login.attempt.clock', self::$data['attempt_clock'], PROFILE_TYPE_INT);
             $result &= CProfile::flush();
         }
         // remove guest session after successful login
         $result &= DBexecute('DELETE FROM sessions WHERE sessionid=' . zbx_dbstr(get_cookie('zbx_sessionid')));
         if ($result) {
             self::setSessionCookie(self::$data['sessionid']);
             add_audit_ext(AUDIT_ACTION_LOGIN, AUDIT_RESOURCE_USER, self::$data['userid'], '', null, null, null);
         }
         return $result;
     } catch (Exception $e) {
         self::setDefault();
         return false;
     }
 }
Beispiel #7
0
function zbx_session_start($userid, $name, $password)
{
    $sessionid = md5(time() . $password . $name . rand(0, 10000000));
    zbx_setcookie('zbx_sessionid', $sessionid);
    DBexecute('INSERT INTO sessions (sessionid,userid,lastaccess,status) VALUES (' . zbx_dbstr($sessionid) . ',' . $userid . ',' . time() . ',' . ZBX_SESSION_ACTIVE . ')');
    return $sessionid;
}
Beispiel #8
0
 /**
  * Get GraphItems data
  *
  * @param array $options
  * @return array|boolean
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     $sqlParts = array('select' => array('gitems' => 'gi.gitemid'), 'from' => array('graphs_items' => 'graphs_items gi'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('graphids' => null, 'itemids' => null, 'type' => null, 'editable' => null, 'nopermissions' => null, 'selectGraphs' => null, 'output' => API_OUTPUT_EXTEND, 'expandData' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     $this->checkDeprecatedParam($options, 'expandData');
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE gi.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY i.itemid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ' AND MAX(r.permission)>=' . zbx_dbstr($permission) . ')';
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         $sqlParts['from']['graphs'] = 'graphs g';
         $sqlParts['where']['gig'] = 'gi.graphid=g.graphid';
         $sqlParts['where'][] = dbConditionInt('g.graphid', $options['graphids']);
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         $sqlParts['where'][] = dbConditionInt('gi.itemid', $options['itemids']);
     }
     // type
     if (!is_null($options['type'])) {
         $sqlParts['where'][] = 'gi.type=' . zbx_dbstr($options['type']);
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $dbRes = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
     while ($gitem = DBfetch($dbRes)) {
         if (!is_null($options['countOutput'])) {
             $result = $gitem['rowscount'];
         } else {
             $result[$gitem['gitemid']] = $gitem;
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     if ($result) {
         $result = $this->addRelatedObjects($options, $result);
         $result = $this->unsetExtraFields($result, array('graphid'), $options['output']);
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $hostids = array();
     $dbHostGroups = DBselect('SELECT DISTINCT hg.hostid FROM hosts_groups hg WHERE hg.groupid=' . zbx_dbstr($this->screenitem['resourceid']));
     while ($dbHostGroup = DBfetch($dbHostGroups)) {
         $hostids[$dbHostGroup['hostid']] = $dbHostGroup['hostid'];
     }
     return $this->getOutput(get_items_data_overview($hostids, $this->screenitem['style']));
 }
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $hostids = array();
     $dbHostGroups = DBselect('SELECT DISTINCT hg.hostid' . ' FROM hosts_groups hg' . ' WHERE hg.groupid=' . zbx_dbstr($this->screenitem['resourceid']));
     while ($dbHostGroup = DBfetch($dbHostGroups)) {
         $hostids[$dbHostGroup['hostid']] = $dbHostGroup['hostid'];
     }
     return $this->getOutput(getTriggersOverview($hostids, $this->screenitem['application'], $this->pageFile, $this->screenitem['style'], $this->screenid));
 }
 /**
  * Check if 'dbversion' table exists.
  *
  * @return bool
  */
 protected function checkDbVersionTable()
 {
     global $DB;
     $tableExists = DBfetch(DBselect('SELECT 1 FROM information_schema.tables' . ' WHERE table_catalog=' . zbx_dbstr($DB['DATABASE']) . " AND table_schema='public'" . " AND table_name='dbversion'"));
     if (!$tableExists) {
         $this->setError(_('The frontend does not match Zabbix database.'));
         return false;
     }
     return true;
 }
Beispiel #12
0
/**
 * Get image data from db, cache is used
 * @param  $imageid
 * @return array image data from db
 */
function get_image_by_imageid($imageid)
{
    static $images = array();
    if (!isset($images[$imageid])) {
        $row = DBfetch(DBselect('SELECT i.* FROM images i WHERE i.imageid=' . zbx_dbstr($imageid)));
        $row['image'] = zbx_unescape_image($row['image']);
        $images[$imageid] = $row;
    }
    return $images[$imageid];
}
Beispiel #13
0
function get_service_children($serviceid, $soft = 0)
{
    $children = [];
    $result = DBselect('SELECT sl.servicedownid' . ' FROM services_links sl' . ' WHERE sl.serviceupid=' . zbx_dbstr($serviceid) . ($soft ? '' : ' AND sl.soft=0'));
    while ($row = DBfetch($result)) {
        $children[] = $row['servicedownid'];
        $children = array_merge($children, get_service_children($row['servicedownid']));
    }
    return $children;
}
Beispiel #14
0
 /**
  * Returns the last $limit history objects for the given items.
  *
  * @param array $items      an array of items with the 'itemid' and 'value_type' properties
  * @param int   $limit
  * @param int   $period     the maximum period to retrieve data for
  *
  * @return array    an array with items IDs as keys and arrays of history objects as values
  */
 public function getLast(array $items, $limit = 1, $period = null)
 {
     $rs = array();
     foreach ($items as $item) {
         $values = DBfetchArray(DBselect('SELECT *' . ' FROM ' . self::getTableName($item['value_type']) . ' h' . ' WHERE h.itemid=' . zbx_dbstr($item['itemid']) . ($period ? ' AND h.clock>' . (time() - $period) : '') . ' ORDER BY h.clock DESC', $limit));
         if ($values) {
             $rs[$item['itemid']] = $values;
         }
     }
     return $rs;
 }
Beispiel #15
0
function add_expression($regexpid, $expression = array())
{
    $db_fields = array('expression' => null, 'expression_type' => null, 'case_sensitive' => 0, 'exp_delimiter' => ',');
    if (!check_db_fields($db_fields, $expression)) {
        error('Incorrect arguments pasted to function [add_expression]');
        return false;
    }
    $expressionid = get_dbid('expressions', 'expressionid');
    $result = DBexecute('INSERT INTO expressions (expressionid,regexpid,expression,expression_type,case_sensitive,exp_delimiter) ' . ' VALUES (' . $expressionid . ',' . $regexpid . ',' . zbx_dbstr($expression['expression']) . ',' . $expression['expression_type'] . ',' . $expression['case_sensitive'] . ',' . zbx_dbstr($expression['exp_delimiter']) . ')');
    return $result ? $expressionid : false;
}
Beispiel #16
0
function add_expression($regexpid, $expression = array())
{
    $db_fields = array('expression' => null, 'expression_type' => null, 'case_sensitive' => 0, 'exp_delimiter' => ',');
    if (!check_db_fields($db_fields, $expression)) {
        error(S_INCORRECT_ARGUMENTS_PASSED_TO_FUNCTION . ' [add_expression]');
        return false;
    }
    $expressionid = get_dbid('expressions', 'expressionid');
    $result = DBexecute('INSERT INTO expressions (expressionid,regexpid,expression,expression_type,case_sensitive,exp_delimiter) ' . ' VALUES (' . $expressionid . ',' . $regexpid . ',' . zbx_dbstr($expression['expression']) . ',' . $expression['expression_type'] . ',' . $expression['case_sensitive'] . ',' . zbx_dbstr($expression['exp_delimiter']) . ')');
    return $result ? $expressionid : false;
}
Beispiel #17
0
 /**
  * Check if 'dbversion' table exists.
  *
  * @return boolean
  */
 protected function checkDbVersionTable()
 {
     global $DB;
     $tabSchema = zbx_dbstr(!empty($DB['SCHEMA']) ? $DB['SCHEMA'] : zbx_strtoupper($DB['USER']));
     $tableExists = DBfetch(DBselect('SELECT 1 FROM SYSCAT.TABLES' . " WHERE TABNAME='DBVERSION'" . " AND TABSCHEMA=" . $tabSchema));
     if (!$tableExists) {
         $this->setError(_('The frontend does not match Zabbix database.'));
         return false;
     }
     return true;
 }
 /**
  * Returns the last $limit history objects for the given items.
  *
  * @param array $items  an array of items with the 'itemid' and 'value_type' properties
  * @param int $limit
  *
  * @return array    an array with items IDs as keys and arrays of history objects as values
  */
 public function getLast(array $items, $limit = 1)
 {
     $rs = array();
     foreach ($items as $item) {
         $table = self::getTableName($item['value_type']);
         $query = DBselect('SELECT *' . ' FROM ' . $table . ' h' . ' WHERE h.itemid=' . zbx_dbstr($item['itemid']) . ' ORDER BY h.clock DESC', $limit);
         while ($history = DBfetch($query)) {
             $rs[$history['itemid']][] = $history;
         }
     }
     return $rs;
 }
Beispiel #19
0
function add_acknowledge_coment($eventid, $userid, $message)
{
    $result = set_event_acnowledged($eventid);
    if (!$result) {
        return $result;
    }
    $acknowledgeid = get_dbid("acknowledges", "acknowledgeid");
    $result = DBexecute("insert into acknowledges (acknowledgeid,userid,eventid,clock,message)" . " values ({$acknowledgeid},{$userid},{$eventid}," . time() . "," . zbx_dbstr($message) . ")");
    if (!$result) {
        return $result;
    }
    return $acknowledgeid;
}
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $hostids = array();
     $dbHostGroups = DBselect('SELECT DISTINCT hg.hostid FROM hosts_groups hg WHERE hg.groupid=' . zbx_dbstr($this->screenitem['resourceid']));
     while ($dbHostGroup = DBfetch($dbHostGroups)) {
         $hostids[$dbHostGroup['hostid']] = $dbHostGroup['hostid'];
     }
     // application filter
     $applicationIds = null;
     if ($this->screenitem['application'] !== '') {
         $applications = API::Application()->get(array('output' => array('applicationid'), 'hostids' => $hostids, 'search' => array('name' => $this->screenitem['application'])));
         $applicationIds = zbx_objectValues($applications, 'applicationid');
     }
     return $this->getOutput(getItemsDataOverview($hostids, $applicationIds, $this->screenitem['style']));
 }
function get_next_event($currentEvent, array $eventList = array(), $showUnknown = false)
{
    $nextEvent = false;
    foreach ($eventList as $event) {
        // check only the events belonging to the same object
        // find the event with the smallest eventid but greater than the current event id
        if ($event['object'] == $currentEvent['object'] && bccomp($event['objectid'], $currentEvent['objectid']) == 0 && (bccomp($event['eventid'], $currentEvent['eventid']) === 1 && (!$nextEvent || bccomp($event['eventid'], $nextEvent['eventid']) === -1))) {
            $nextEvent = $event;
        }
    }
    if ($nextEvent) {
        return $nextEvent;
    }
    $sql = 'SELECT e.*' . ' FROM events e' . ' WHERE e.objectid=' . zbx_dbstr($currentEvent['objectid']) . ' AND e.eventid>' . zbx_dbstr($currentEvent['eventid']) . ' AND e.object=' . zbx_dbstr($currentEvent['object']) . ($showUnknown ? '' : ' AND e.value_changed=' . TRIGGER_VALUE_CHANGED_YES) . ' ORDER BY e.object,e.objectid,e.eventid';
    return DBfetch(DBselect($sql, 1));
}
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $total = 0;
     // fetch accessible host ids
     $hosts = API::Host()->get(['output' => ['hostid'], 'preservekeys' => true]);
     $hostids = array_keys($hosts);
     if ($this->screenitem['resourceid'] != 0) {
         $cond_from = ',hosts_groups hg';
         $cond_where = ' AND hg.hostid=h.hostid AND hg.groupid=' . zbx_dbstr($this->screenitem['resourceid']);
     } else {
         $cond_from = '';
         $cond_where = '';
     }
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_TRUE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $avail = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_FALSE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $notav = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_UNKNOWN . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $uncn = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $avail = (new CCol($avail . '  ' . _('Available')))->addClass(ZBX_STYLE_GREEN);
     $notav = (new CCol($notav . '  ' . _('Not available')))->addClass(ZBX_STYLE_RED);
     $uncn = (new CCol($uncn . '  ' . _('Unknown')))->addClass(ZBX_STYLE_GREY);
     $total = new CCol($total . '  ' . _('Total'));
     $header = (new CDiv([new CTag('h4', true, _('Hosts info'))]))->addClass(ZBX_STYLE_DASHBRD_WIDGET_HEAD);
     if ($this->screenitem['resourceid'] != 0) {
         $groups = API::HostGroup()->get(['output' => ['name'], 'groupids' => [$this->screenitem['resourceid']]]);
         $header->addItem((new CList())->addItem([_('Group'), ':', SPACE, $groups[0]['name']]));
     }
     $table = new CTableInfo();
     if ($this->screenitem['style'] == STYLE_HORIZONTAL) {
         $table->addRow([$avail, $notav, $uncn, $total]);
     } else {
         $table->addRow($avail);
         $table->addRow($notav);
         $table->addRow($uncn);
         $table->addRow($total);
     }
     $footer = (new CList())->addItem(_s('Updated: %s', zbx_date2str(TIME_FORMAT_SECONDS)))->addClass(ZBX_STYLE_DASHBRD_WIDGET_FOOT);
     return $this->getOutput(new CUiWidget(uniqid(), [$header, $table, $footer]));
 }
function replace_value_by_map($value, $valuemapid)
{
    if ($valuemapid < 1) {
        return $value;
    }
    static $valuemaps = array();
    if (isset($valuemaps[$valuemapid][$value])) {
        return $valuemaps[$valuemapid][$value];
    }
    $sql = 'SELECT newvalue ' . ' FROM mappings ' . ' WHERE valuemapid=' . $valuemapid . ' AND value=' . zbx_dbstr($value);
    $result = DBselect($sql);
    if ($row = DBfetch($result)) {
        $valuemaps[$valuemapid][$value] = $row['newvalue'] . ' ' . '(' . $value . ')';
        return $valuemaps[$valuemapid][$value];
    }
    return $value;
}
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $hostids = [];
     $dbHostGroups = DBselect('SELECT DISTINCT hg.hostid FROM hosts_groups hg WHERE hg.groupid=' . zbx_dbstr($this->screenitem['resourceid']));
     while ($dbHostGroup = DBfetch($dbHostGroups)) {
         $hostids[$dbHostGroup['hostid']] = $dbHostGroup['hostid'];
     }
     // application filter
     $applicationIds = null;
     if ($this->screenitem['application'] !== '') {
         $applications = API::Application()->get(['output' => ['applicationid'], 'hostids' => $hostids, 'search' => ['name' => $this->screenitem['application']]]);
         $applicationIds = zbx_objectValues($applications, 'applicationid');
     }
     $groups = API::HostGroup()->get(['output' => ['name'], 'groupids' => [$this->screenitem['resourceid']]]);
     $header = (new CDiv([new CTag('h4', true, _('Data overview')), (new CList())->addItem([_('Group'), ':', SPACE, $groups[0]['name']])]))->addClass(ZBX_STYLE_DASHBRD_WIDGET_HEAD);
     $table = getItemsDataOverview($hostids, $applicationIds, $this->screenitem['style']);
     $footer = (new CList())->addItem(_s('Updated: %s', zbx_date2str(TIME_FORMAT_SECONDS)))->addClass(ZBX_STYLE_DASHBRD_WIDGET_FOOT);
     return $this->getOutput(new CUiWidget(uniqid(), [$header, $table, $footer]));
 }
 /**
  * Initialize expression, gets data from db for Zabbix expressions.
  * @throws Exception
  * @param string $regExp
  */
 public function __construct($regExp)
 {
     if ($regExp[0] == '@') {
         $this->isZabbixRegexp = true;
         $regExp = substr($regExp, 1);
         if (!isset(self::$_cachedExpressions[$regExp])) {
             self::$_cachedExpressions[$regExp] = array();
             $dbRegExps = DBselect('SELECT e.regexpid,e.expression,e.expression_type,e.exp_delimiter,e.case_sensitive' . ' FROM expressions e,regexps r' . ' WHERE e.regexpid=r.regexpid' . ' AND r.name=' . zbx_dbstr($regExp));
             while ($expression = DBfetch($dbRegExps)) {
                 self::$_cachedExpressions[$regExp][] = $expression;
             }
             if (empty(self::$_cachedExpressions[$regExp])) {
                 unset(self::$_cachedExpressions[$regExp]);
                 throw new Exception('Does not exist', self::ERROR_REGEXP_NOT_EXISTS);
             }
         }
         $this->expression = self::$_cachedExpressions[$regExp];
     } else {
         $this->isZabbixRegexp = false;
         $this->expression = $regExp;
     }
 }
 /**
  * Get Itemprototype data.
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     $sqlParts = array('select' => array('items' => 'i.itemid'), 'from' => array('items' => 'items i'), 'where' => array('i.flags=' . ZBX_FLAG_DISCOVERY_PROTOTYPE), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('groupids' => null, 'templateids' => null, 'hostids' => null, 'itemids' => null, 'discoveryids' => null, 'graphids' => null, 'triggerids' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectHosts' => null, 'selectApplications' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectDiscoveryRule' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE i.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ' AND MAX(r.permission)>=' . zbx_dbstr($permission) . ')';
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if (!is_null($options['hostids'])) {
             zbx_value2array($options['hostids']);
             $options['hostids'] = array_merge($options['hostids'], $options['templateids']);
         } else {
             $options['hostids'] = $options['templateids'];
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['hostids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['i'] = 'i.hostid';
         }
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         $sqlParts['where']['itemid'] = dbConditionInt('i.itemid', $options['itemids']);
     }
     // discoveryids
     if (!is_null($options['discoveryids'])) {
         zbx_value2array($options['discoveryids']);
         $sqlParts['from']['item_discovery'] = 'item_discovery id';
         $sqlParts['where'][] = dbConditionInt('id.parent_itemid', $options['discoveryids']);
         $sqlParts['where']['idi'] = 'i.itemid=id.itemid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['id'] = 'id.parent_itemid';
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']);
         $sqlParts['where']['if'] = 'i.itemid=f.itemid';
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']);
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sqlParts['where'][] = 'i.templateid IS NOT NULL';
         } else {
             $sqlParts['where'][] = 'i.templateid IS NULL';
         }
     }
     // templated
     if (!is_null($options['templated'])) {
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['templated']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
         } else {
             $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE;
         }
     }
     // monitored
     if (!is_null($options['monitored'])) {
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['monitored']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_MONITORED;
             $sqlParts['where'][] = 'i.status=' . ITEM_STATUS_ACTIVE;
         } else {
             $sqlParts['where'][] = '(h.status<>' . HOST_STATUS_MONITORED . ' OR i.status<>' . ITEM_STATUS_ACTIVE . ')';
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('items i', $options, $sqlParts);
     }
     // --- FILTER ---
     if (is_array($options['filter'])) {
         $this->dbFilter('items i', $options, $sqlParts);
         if (isset($options['filter']['host'])) {
             zbx_value2array($options['filter']['host']);
             $sqlParts['from']['hosts'] = 'hosts h';
             $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
             $sqlParts['where']['h'] = dbConditionString('h.host', $options['filter']['host']);
         }
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     //----------
     $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
     while ($item = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $item;
             } else {
                 $result = $item['rowscount'];
             }
         } else {
             $result[$item['itemid']] = $item;
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // add other related objects
     if ($result) {
         $result = $this->addRelatedObjects($options, $result);
         $result = $this->unsetExtraFields($result, array('hostid'), $options['output']);
     }
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Beispiel #27
0
/**
 * Get parent maps for current map.
 *
 * @param int $mapId
 *
 * @return array
 */
function getParentMaps($mapId)
{
    $parentMaps = DBfetchArrayAssoc(DBselect('SELECT s.sysmapid,s.name' . ' FROM sysmaps s' . ' JOIN sysmaps_elements se ON se.sysmapid=s.sysmapid' . ' WHERE se.elementtype=' . SYSMAP_ELEMENT_TYPE_MAP . ' AND se.elementid=' . zbx_dbstr($mapId)), 'sysmapid');
    CArrayHelper::sort($parentMaps, array('name'));
    return $parentMaps;
}
Beispiel #28
0
        case AUDIT_ACTION_LOGOUT:
            $action = _('Logout');
            break;
        case AUDIT_ACTION_ENABLE:
            $action = _('Enabled');
            break;
        case AUDIT_ACTION_DISABLE:
            $action = _('Disabled');
            break;
        default:
            $action = _('Unknown action');
    }
    $audit['action'] = $action;
    $audit['resourcetype'] = audit_resource2str($audit['resourcetype']);
    if (empty($audit['details'])) {
        $audit['details'] = DBfetchArray(DBselect('SELECT ad.table_name,ad.field_name,ad.oldvalue,ad.newvalue' . ' FROM auditlog_details ad' . ' WHERE ad.auditid=' . zbx_dbstr($audit['auditid'])));
    }
    $data['actions'][$audit['auditid']] = $audit;
}
if (!empty($data['actions'])) {
    order_result($data['actions'], 'clock', ZBX_SORT_DOWN);
}
// get paging
$data['paging'] = getPagingLine($data['actions'], ZBX_SORT_DOWN, new CUrl('auditlogs.php'));
// get timeline
unset($sqlWhere['from'], $sqlWhere['till']);
$sql = 'SELECT MIN(a.clock) AS clock' . ' FROM auditlog a,users u' . ' WHERE a.userid=u.userid' . implode('', $sqlWhere);
$firstAudit = DBfetch(DBselect($sql, $config['search_limit'] + 1));
$data['timeline'] = ['period' => $effectivePeriod, 'starttime' => date(TIMESTAMP_FORMAT, $firstAudit ? $firstAudit['clock'] : null), 'usertime' => isset($_REQUEST['stime']) ? date(TIMESTAMP_FORMAT, zbxDateToTime($data['stime']) + $effectivePeriod) : null];
// render view
$auditView = new CView('administration.auditlogs.list', $data);
Beispiel #29
0
    fatal_error(_('No triggers defined.'));
}
/*
 * Permissions
 */
$trigger = API::Trigger()->get(['triggerids' => $_REQUEST['triggerid'], 'output' => API_OUTPUT_EXTEND, 'expandDescription' => true]);
if (!$trigger) {
    access_deny();
}
$trigger = reset($trigger);
/*
 * Actions
 */
if (hasRequest('update')) {
    DBstart();
    $result = DBexecute('UPDATE triggers' . ' SET comments=' . zbx_dbstr(getRequest('comments')) . ' WHERE triggerid=' . zbx_dbstr(getRequest('triggerid')));
    $trigger['comments'] = $_REQUEST['comments'];
    if ($result) {
        add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_TRIGGER, _('Trigger') . ' [' . $_REQUEST['triggerid'] . '] [' . $trigger['description'] . '] ' . _('Comments') . ' [' . $_REQUEST['comments'] . ']');
    }
    $result = DBend($result);
    show_messages($result, _('Description updated'), _('Cannot update description'));
} elseif (isset($_REQUEST['cancel'])) {
    jsRedirect('tr_status.php');
    exit;
}
/*
 * Display
 */
$triggerEditable = API::Trigger()->get(['triggerids' => $_REQUEST['triggerid'], 'output' => ['triggerid'], 'editable' => true]);
$data = ['triggerid' => getRequest('triggerid'), 'trigger' => $trigger, 'isTriggerEditable' => !empty($triggerEditable), 'isCommentExist' => !empty($trigger['comments'])];
 /**
  * Mass update hosts
  *
  * @param _array $hosts multidimensional array with Hosts data
  * @param array $hosts['hosts'] Array of Host objects to update
  * @param string $hosts['fields']['host'] Host name.
  * @param array $hosts['fields']['groupids'] HostGroup IDs add Host to.
  * @param int $hosts['fields']['port'] Port. OPTIONAL
  * @param int $hosts['fields']['status'] Host Status. OPTIONAL
  * @param int $hosts['fields']['useip'] Use IP. OPTIONAL
  * @param string $hosts['fields']['dns'] DNS. OPTIONAL
  * @param string $hosts['fields']['ip'] IP. OPTIONAL
  * @param int $hosts['fields']['proxy_hostid'] Proxy Host ID. OPTIONAL
  * @param int $hosts['fields']['useipmi'] Use IPMI. OPTIONAL
  * @param string $hosts['fields']['ipmi_ip'] IPMAI IP. OPTIONAL
  * @param int $hosts['fields']['ipmi_port'] IPMI port. OPTIONAL
  * @param int $hosts['fields']['ipmi_authtype'] IPMI authentication type. OPTIONAL
  * @param int $hosts['fields']['ipmi_privilege'] IPMI privilege. OPTIONAL
  * @param string $hosts['fields']['ipmi_username'] IPMI username. OPTIONAL
  * @param string $hosts['fields']['ipmi_password'] IPMI password. OPTIONAL
  * @return boolean
  */
 public static function massUpdate($data)
 {
     $hosts = zbx_toArray($data['hosts']);
     $hostids = zbx_objectValues($hosts, 'hostid');
     try {
         self::BeginTransaction(__METHOD__);
         $options = array('hostids' => $hostids, 'editable' => 1, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1);
         $upd_hosts = self::get($options);
         foreach ($hosts as $hnum => $host) {
             if (!isset($upd_hosts[$host['hostid']])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
             }
         }
         // CHECK IF HOSTS HAVE AT LEAST 1 GROUP {{{
         if (isset($data['groups']) && empty($data['groups'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'No groups for hosts');
         }
         // }}} CHECK IF HOSTS HAVE AT LEAST 1 GROUP
         // UPDATE HOSTS PROPERTIES {{{
         if (isset($data['host'])) {
             if (count($hosts) > 1) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot mass update host name');
             }
             $cur_host = reset($hosts);
             $options = array('filter' => array('host' => $cur_host['host']), 'output' => API_OUTPUT_SHORTEN, 'editable' => 1, 'nopermissions' => 1);
             $host_exists = self::get($options);
             $host_exist = reset($host_exists);
             if ($host_exist && $host_exist['hostid'] != $cur_host['hostid']) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_HOST . ' [ ' . $data['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL);
             }
             //can't add host with the same name as existing template
             if (CTemplate::exists(array('host' => $cur_host['host']))) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_TEMPLATE . ' [ ' . $cur_host['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL);
             }
         }
         if (isset($data['host']) && !preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/i', $data['host'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for Hostname [ ' . $data['host'] . ' ]');
         }
         if (isset($data['dns']) && !empty($data['dns']) && !preg_match('/^' . ZBX_PREG_DNS_FORMAT . '$/i', $data['dns'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for DNS [ ' . $data['dns'] . ' ]');
         }
         $sql_set = array();
         if (isset($data['proxy_hostid'])) {
             $sql_set[] = 'proxy_hostid=' . $data['proxy_hostid'];
         }
         if (isset($data['host'])) {
             $sql_set[] = 'host=' . zbx_dbstr($data['host']);
         }
         if (isset($data['port'])) {
             $sql_set[] = 'port=' . $data['port'];
         }
         if (isset($data['status'])) {
             $sql_set[] = 'status=' . $data['status'];
         }
         if (isset($data['useip'])) {
             $sql_set[] = 'useip=' . $data['useip'];
         }
         if (isset($data['dns'])) {
             $sql_set[] = 'dns=' . zbx_dbstr($data['dns']);
         }
         if (isset($data['ip'])) {
             $sql_set[] = 'ip=' . zbx_dbstr($data['ip']);
         }
         if (isset($data['useipmi'])) {
             $sql_set[] = 'useipmi=' . $data['useipmi'];
         }
         if (isset($data['ipmi_port'])) {
             $sql_set[] = 'ipmi_port=' . $data['ipmi_port'];
         }
         if (isset($data['ipmi_authtype'])) {
             $sql_set[] = 'ipmi_authtype=' . $data['ipmi_authtype'];
         }
         if (isset($data['ipmi_privilege'])) {
             $sql_set[] = 'ipmi_privilege=' . $data['ipmi_privilege'];
         }
         if (isset($data['ipmi_username'])) {
             $sql_set[] = 'ipmi_username='******'ipmi_username']);
         }
         if (isset($data['ipmi_password'])) {
             $sql_set[] = 'ipmi_password='******'ipmi_password']);
         }
         if (isset($data['ipmi_ip'])) {
             $sql_set[] = 'ipmi_ip=' . zbx_dbstr($data['ipmi_ip']);
         }
         if (!empty($sql_set)) {
             $sql = 'UPDATE hosts SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $hostids);
             $result = DBexecute($sql);
             if (isset($data['status'])) {
                 update_host_status($hostids, $data['status']);
             }
         }
         // }}} UPDATE HOSTS PROPERTIES
         // UPDATE HOSTGROUPS LINKAGE {{{
         if (isset($data['groups']) && !is_null($data['groups'])) {
             $data['groups'] = zbx_toArray($data['groups']);
             $host_groups = CHostGroup::get(array('hostids' => $hostids));
             $host_groupids = zbx_objectValues($host_groups, 'groupid');
             $new_groupids = zbx_objectValues($data['groups'], 'groupid');
             $groups_to_add = array_diff($new_groupids, $host_groupids);
             if (!empty($groups_to_add)) {
                 $result = self::massAdd(array('hosts' => $hosts, 'groups' => zbx_toObject($groups_to_add, 'groupid')));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t add group');
                 }
             }
             $groupids_to_del = array_diff($host_groupids, $new_groupids);
             if (!empty($groupids_to_del)) {
                 $result = self::massRemove(array('hostids' => $hostids, 'groupids' => $groupids_to_del));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t remove group');
                 }
             }
         }
         // }}} UPDATE HOSTGROUPS LINKAGE
         $data['templates_clear'] = isset($data['templates_clear']) ? zbx_toArray($data['templates_clear']) : array();
         $cleared_templateids = array();
         foreach ($hostids as $hostid) {
             foreach ($data['templates_clear'] as $tpl) {
                 $result = unlink_template($hostid, $tpl['templateid'], false);
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot unlink template [ ' . $tpl['templateid'] . ' ]');
                 }
                 $cleared_templateids[] = $tpl['templateid'];
             }
         }
         // UPDATE TEMPLATE LINKAGE {{{
         if (isset($data['templates']) && !is_null($data['templates'])) {
             $opt = array('hostids' => $hostids, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true);
             $host_templates = CTemplate::get($opt);
             $host_templateids = array_keys($host_templates);
             $new_templateids = zbx_objectValues($data['templates'], 'templateid');
             $templates_to_del = array_diff($host_templateids, $new_templateids);
             $templates_to_del = array_diff($templates_to_del, $cleared_templateids);
             if (!empty($templates_to_del)) {
                 $result = self::massRemove(array('hostids' => $hostids, 'templateids' => $templates_to_del));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, S_CANNOT_UNLINK_TEMPLATE);
                 }
             }
             $result = self::massAdd(array('hosts' => $hosts, 'templates' => $data['templates']));
             if (!$result) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_CANNOT_LINK_TEMPLATE);
             }
         }
         // }}} UPDATE TEMPLATE LINKAGE
         // UPDATE MACROS {{{
         if (isset($data['macros']) && !is_null($data['macros'])) {
             $macrosToAdd = zbx_toHash($data['macros'], 'macro');
             $hostMacros = CUserMacro::get(array('hostids' => $hostids, 'output' => API_OUTPUT_EXTEND));
             $hostMacros = zbx_toHash($hostMacros, 'macro');
             // Delete
             $macrosToDelete = array();
             foreach ($hostMacros as $hmnum => $hmacro) {
                 if (!isset($macrosToAdd[$hmacro['macro']])) {
                     $macrosToDelete[] = $hmacro['macro'];
                 }
             }
             // Update
             $macrosToUpdate = array();
             foreach ($macrosToAdd as $nhmnum => $nhmacro) {
                 if (isset($hostMacros[$nhmacro['macro']])) {
                     $macrosToUpdate[] = $nhmacro;
                     unset($macrosToAdd[$nhmnum]);
                 }
             }
             //----
             if (!empty($macrosToDelete)) {
                 $result = self::massRemove(array('hostids' => $hostids, 'macros' => $macrosToDelete));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t remove macro');
                 }
             }
             if (!empty($macrosToUpdate)) {
                 $result = CUsermacro::massUpdate(array('hosts' => $hosts, 'macros' => $macrosToUpdate));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update macro');
                 }
             }
             if (!empty($macrosToAdd)) {
                 $result = self::massAdd(array('hosts' => $hosts, 'macros' => $macrosToAdd));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot add macro');
                 }
             }
         }
         // }}} UPDATE MACROS
         // PROFILE {{{
         if (isset($data['profile']) && !is_null($data['profile'])) {
             if (empty($data['profile'])) {
                 $sql = 'DELETE FROM hosts_profiles WHERE ' . DBcondition('hostid', $hostids);
                 if (!DBexecute($sql)) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot delete profile');
                 }
             } else {
                 $existing_profiles = array();
                 $existing_profiles_db = DBselect('SELECT hostid FROM hosts_profiles WHERE ' . DBcondition('hostid', $hostids));
                 while ($existing_profile = DBfetch($existing_profiles_db)) {
                     $existing_profiles[] = $existing_profile['hostid'];
                 }
                 $hostids_without_profile = array_diff($hostids, $existing_profiles);
                 $fields = array_keys($data['profile']);
                 $fields = implode(', ', $fields);
                 $values = array_map('zbx_dbstr', $data['profile']);
                 $values = implode(', ', $values);
                 foreach ($hostids_without_profile as $hostid) {
                     $sql = 'INSERT INTO hosts_profiles (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')';
                     if (!DBexecute($sql)) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot create profile');
                     }
                 }
                 if (!empty($existing_profiles)) {
                     $host_profile_fields = array('devicetype', 'name', 'os', 'serialno', 'tag', 'macaddress', 'hardware', 'software', 'contact', 'location', 'notes');
                     $sql_set = array();
                     foreach ($host_profile_fields as $field) {
                         if (isset($data['profile'][$field])) {
                             $sql_set[] = $field . '=' . zbx_dbstr($data['profile'][$field]);
                         }
                     }
                     $sql = 'UPDATE hosts_profiles SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $existing_profiles);
                     if (!DBexecute($sql)) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update profile');
                     }
                 }
             }
         }
         // }}} PROFILE
         // EXTENDED PROFILE {{{
         if (isset($data['extendedProfile']) && !is_null($data['extendedProfile'])) {
             if (empty($data['extendedProfile'])) {
                 $sql = 'DELETE FROM hosts_profiles_ext WHERE ' . DBcondition('hostid', $hostids);
                 if (!DBexecute($sql)) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot delete extended profile');
                 }
             } else {
                 $existing_profiles = array();
                 $existing_profiles_db = DBselect('SELECT hostid FROM hosts_profiles_ext WHERE ' . DBcondition('hostid', $hostids));
                 while ($existing_profile = DBfetch($existing_profiles_db)) {
                     $existing_profiles[] = $existing_profile['hostid'];
                 }
                 $hostids_without_profile = array_diff($hostids, $existing_profiles);
                 $fields = array_keys($data['extendedProfile']);
                 $fields = implode(', ', $fields);
                 $values = array_map('zbx_dbstr', $data['extendedProfile']);
                 $values = implode(', ', $values);
                 foreach ($hostids_without_profile as $hostid) {
                     $sql = 'INSERT INTO hosts_profiles_ext (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')';
                     if (!DBexecute($sql)) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot create extended profile');
                     }
                 }
                 if (!empty($existing_profiles)) {
                     $host_profile_ext_fields = array('device_alias', 'device_type', 'device_chassis', 'device_os', 'device_os_short', 'device_hw_arch', 'device_serial', 'device_model', 'device_tag', 'device_vendor', 'device_contract', 'device_who', 'device_status', 'device_app_01', 'device_app_02', 'device_app_03', 'device_app_04', 'device_app_05', 'device_url_1', 'device_url_2', 'device_url_3', 'device_networks', 'device_notes', 'device_hardware', 'device_software', 'ip_subnet_mask', 'ip_router', 'ip_macaddress', 'oob_ip', 'oob_subnet_mask', 'oob_router', 'date_hw_buy', 'date_hw_install', 'date_hw_expiry', 'date_hw_decomm', 'site_street_1', 'site_street_2', 'site_street_3', 'site_city', 'site_state', 'site_country', 'site_zip', 'site_rack', 'site_notes', 'poc_1_name', 'poc_1_email', 'poc_1_phone_1', 'poc_1_phone_2', 'poc_1_cell', 'poc_1_screen', 'poc_1_notes', 'poc_2_name', 'poc_2_email', 'poc_2_phone_1', 'poc_2_phone_2', 'poc_2_cell', 'poc_2_screen', 'poc_2_notes');
                     $sql_set = array();
                     foreach ($host_profile_ext_fields as $field) {
                         if (isset($data['extendedProfile'][$field])) {
                             $sql_set[] = $field . '=' . zbx_dbstr($data['extendedProfile'][$field]);
                         }
                     }
                     $sql = 'UPDATE hosts_profiles_ext SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $existing_profiles);
                     if (!DBexecute($sql)) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update extended profile');
                     }
                 }
             }
         }
         // }}} EXTENDED PROFILE
         self::EndTransaction(true, __METHOD__);
         return array('hostids' => $hostids);
     } catch (APIException $e) {
         self::EndTransaction(false, __METHOD__);
         $error = $e->getErrors();
         $error = reset($error);
         self::setError(__METHOD__, $e->getCode(), $error);
         return false;
     }
 }