public function addItem($value, $caption = '', $selected = null, $enabled = 'yes')
 {
     if ($value instanceof CComboItem || $value instanceof COptGroup) {
         parent::addItem($value);
     } else {
         $title = false;
         // if caption is too long ( > 44 symbols), we add new class - 'selectShorten',
         // so that the select box would not stretch
         if (zbx_strlen($caption) > 44 && !$this->hasClass('selectShorten')) {
             $this->setAttribute('class', $this->getAttribute('class') . ' selectShorten');
             $title = true;
         }
         if (is_null($selected)) {
             $selected = 'no';
             if (is_array($this->value)) {
                 if (str_in_array($value, $this->value)) {
                     $selected = 'yes';
                 }
             } elseif (strcmp($value, $this->value) == 0) {
                 $selected = 'yes';
             }
         } else {
             $selected = 'yes';
         }
         $citem = new CComboItem($value, $caption, $selected, $enabled);
         if ($title) {
             $citem->setTitle($caption);
         }
         parent::addItem($citem);
     }
 }
Пример #2
0
function add_audit_details($action, $resourcetype, $resourceid, $resourcename, $details = null)
{
    if (zbx_strlen($resourcename) > 255) {
        $resourcename = zbx_substr($resourcename, 0, 252) . '...';
    }
    $ip = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
    $values = array('userid' => CWebUser::$data['userid'], 'clock' => time(), 'ip' => substr($ip, 0, 39), 'action' => $action, 'resourcetype' => $resourcetype, 'resourceid' => $resourceid, 'resourcename' => $resourcename, 'details' => $details);
    try {
        DB::insert('auditlog', array($values));
        return true;
    } catch (DBException $e) {
        return false;
    }
}
Пример #3
0
function make_decoration($haystack, $needle, $class = null)
{
    $result = $haystack;
    $pos = zbx_stripos($haystack, $needle);
    if ($pos !== false) {
        $start = zbx_substring($haystack, 0, $pos);
        $end = zbx_substring($haystack, $pos + zbx_strlen($needle));
        $found = zbx_substring($haystack, $pos, $pos + zbx_strlen($needle));
        if (is_null($class)) {
            $result = array($start, bold($found), $end);
        } else {
            $result = array($start, new CSpan($found, $class), $end);
        }
    }
    return $result;
}
Пример #4
0
function make_decoration($haystack, $needle, $class = null)
{
    $result = $haystack;
    $pos = stripos($haystack, $needle);
    if ($pos !== FALSE) {
        $start = zbx_substring($haystack, 0, $pos);
        //			$middle = substr($haystack, $pos, zbx_strlen($needle));
        $middle = $needle;
        $end = substr($haystack, $pos + zbx_strlen($needle));
        if (is_null($class)) {
            $result = array($start, bold($middle), $end);
        } else {
            $result = array($start, new CSpan($middle, $class), $end);
        }
    }
    return $result;
}
Пример #5
0
 /**
  * Checks if the given string is:
  * - empty
  * - not too long
  * - matches a certain regex
  *
  * @param string $value
  *
  * @return bool
  */
 public function validate($value)
 {
     if (zbx_empty($value)) {
         if ($this->empty) {
             return true;
         } else {
             $this->error($this->messageEmpty);
             return false;
         }
     }
     if ($this->maxLength && zbx_strlen($value) > $this->maxLength) {
         $this->error($this->messageMaxLength, $this->maxLength);
         return false;
     }
     if ($this->regex && !zbx_empty($value) && !preg_match($this->regex, $value)) {
         $this->error($this->messageRegex, $value);
         return false;
     }
     return true;
 }
 public function checkExpression($expression)
 {
     $length = zbx_strlen($expression);
     $symbolNum = 0;
     try {
         if (zbx_empty(trim($expression))) {
             throw new Exception('Empty expression.');
         }
         // Check expr start symbol
         $startSymbol = zbx_substr(trim($expression), 0, 1);
         if ($startSymbol != '(' && $startSymbol != '{' && $startSymbol != '-' && !zbx_ctype_digit($startSymbol)) {
             throw new Exception('Incorrect trigger expression.');
         }
         for ($symbolNum = 0; $symbolNum < $length; $symbolNum++) {
             $symbol = zbx_substr($expression, $symbolNum, 1);
             // SDI($symbol);
             $this->parseOpenParts($this->previous['last']);
             $this->parseCloseParts($symbol);
             // SDII($this->currExpr);
             if ($this->inParameter($symbol)) {
                 $this->setPreviousSymbol($symbol);
                 continue;
             }
             $this->checkSymbolSequence($symbol);
             $this->setPreviousSymbol($symbol);
             // SDII($this->symbols);
         }
         $symbolNum = 0;
         $simpleExpression = $expression;
         $this->checkBraces();
         $this->checkParts($simpleExpression);
         $this->checkSimpleExpression($simpleExpression);
     } catch (Exception $e) {
         $symbolNum = $symbolNum > 0 ? --$symbolNum : $symbolNum;
         $this->errors[] = $e->getMessage();
         $this->errors[] = 'Check expression part starting from " ' . zbx_substr($expression, $symbolNum) . ' "';
     }
 }
Пример #7
0
function add_audit_ext($action, $resourcetype, $resourceid, $resourcename, $table_name, $values_old, $values_new)
{
    global $USER_DETAILS;
    if (!isset($USER_DETAILS["userid"])) {
        check_authorisation();
    }
    if ($action == AUDIT_ACTION_UPDATE) {
        $values_diff = array();
        foreach ($values_new as $id => $value) {
            if ($values_old[$id] !== $value) {
                array_push($values_diff, $id);
            }
        }
        if (0 == count($values_diff)) {
            return true;
        }
    }
    $auditid = get_dbid('auditlog', 'auditid');
    if (zbx_strlen($resourcename) > 255) {
        $details = substr($resourcename, 0, 252) . '...';
    }
    $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
    /*SDI(
    		'INSERT INTO auditlog (auditid,userid,clock,ip,action,resourcetype,resourceid,resourcename)'.
    		' values ('.$auditid.','.$USER_DETAILS['userid'].','.time().','.zbx_dbstr($ip).
    		','.$action.','.$resourcetype.','.$resourceid.','.zbx_dbstr($resourcename).')');*/
    $result = DBexecute('INSERT INTO auditlog (auditid,userid,clock,ip,action,resourcetype,resourceid,resourcename)' . ' values (' . $auditid . ',' . $USER_DETAILS['userid'] . ',' . time() . ',' . zbx_dbstr($ip) . ',' . $action . ',' . $resourcetype . ',' . $resourceid . ',' . zbx_dbstr($resourcename) . ')');
    if ($result && $action == AUDIT_ACTION_UPDATE) {
        foreach ($values_diff as $id) {
            $auditdetailid = get_dbid('auditlog_details', 'auditdetailid');
            $result &= DBexecute('insert into auditlog_details (auditdetailid,auditid,table_name,field_name,oldvalue,newvalue)' . ' values (' . $auditdetailid . ',' . $auditid . ',' . zbx_dbstr($table_name) . ',' . zbx_dbstr($id) . ',' . zbx_dbstr($values_old[$id]) . ',' . zbx_dbstr($values_new[$id]) . ')');
        }
    }
    if ($result) {
        $result = $auditid;
    }
    return $result;
}
Пример #8
0
 public function addItem($value, $caption = '', $selected = NULL, $enabled = 'yes')
 {
     //			if($enabled=='no') return;	/* disable item method 1 */
     if (is_object($value) && zbx_strtolower(get_class($value)) == 'ccomboitem') {
         parent::addItem($value);
     } else {
         if (zbx_strlen($caption) > 44) {
             $this->setAttribute('class', 'select selectShorten');
         }
         if (is_null($selected)) {
             $selected = 'no';
             if (is_array($this->value)) {
                 if (str_in_array($value, $this->value)) {
                     $selected = 'yes';
                 }
             } else {
                 if (strcmp($value, $this->value) == 0) {
                     $selected = 'yes';
                 }
             }
         }
         parent::addItem(new CComboItem($value, $caption, $selected, $enabled));
     }
 }
Пример #9
0
if (get_request('hostid') && !API::Host()->isWritable(array($_REQUEST['hostid']))) {
    access_deny();
}
/*
 * Actions
 */
if (isset($_REQUEST['add_expression'])) {
    $_REQUEST['expression'] = $_REQUEST['expr_temp'];
    $_REQUEST['expr_temp'] = '';
} elseif (isset($_REQUEST['and_expression'])) {
    $_REQUEST['expr_action'] = '&';
} elseif (isset($_REQUEST['or_expression'])) {
    $_REQUEST['expr_action'] = '|';
} elseif (isset($_REQUEST['replace_expression'])) {
    $_REQUEST['expr_action'] = 'r';
} elseif (isset($_REQUEST['remove_expression']) && zbx_strlen($_REQUEST['remove_expression'])) {
    $_REQUEST['expr_action'] = 'R';
    $_REQUEST['expr_target_single'] = $_REQUEST['remove_expression'];
} elseif (isset($_REQUEST['clone']) && isset($_REQUEST['triggerid'])) {
    unset($_REQUEST['triggerid']);
    $_REQUEST['form'] = 'clone';
} elseif (isset($_REQUEST['save'])) {
    $trigger = array('expression' => $_REQUEST['expression'], 'description' => $_REQUEST['description'], 'priority' => $_REQUEST['priority'], 'status' => $_REQUEST['status'], 'type' => $_REQUEST['type'], 'comments' => $_REQUEST['comments'], 'url' => $_REQUEST['url'], 'dependencies' => zbx_toObject(get_request('dependencies', array()), 'triggerid'));
    if (get_request('triggerid')) {
        // update only changed fields
        $oldTrigger = API::Trigger()->get(array('triggerids' => $_REQUEST['triggerid'], 'output' => API_OUTPUT_EXTEND, 'selectDependencies' => array('triggerid')));
        if (!$oldTrigger) {
            access_deny();
        }
        $oldTrigger = reset($oldTrigger);
        $oldTrigger['dependencies'] = zbx_toHash(zbx_objectValues($oldTrigger['dependencies'], 'triggerid'));
Пример #10
0
 protected function checkInput(&$hosts, $method)
 {
     $create = $method == 'create';
     $update = $method == 'update';
     $hostDBfields = $update ? array('hostid' => null) : array('host' => null);
     if ($update) {
         $dbHosts = $this->get(array('output' => array('hostid', 'host', 'flags'), 'hostids' => zbx_objectValues($hosts, 'hostid'), 'editable' => true, 'preservekeys' => true));
     } else {
         $groupids = array();
         foreach ($hosts as $host) {
             if (!isset($host['groups'])) {
                 continue;
             }
             $groupids = array_merge($groupids, zbx_objectValues($host['groups'], 'groupid'));
         }
         if ($groupids) {
             $dbGroups = API::HostGroup()->get(array('output' => array('groupid'), 'groupids' => $groupids, 'editable' => true, 'preservekeys' => true));
         }
     }
     foreach ($hosts as $host) {
         // validate mandatory fields
         if (!check_db_fields($hostDBfields, $host)) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Wrong fields for host "%s".', isset($host['host']) ? $host['host'] : ''));
         }
         if ($update) {
             $hostId = $host['hostid'];
             // validate host permissions
             if (!isset($dbHosts[$hostId])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
             }
             if (isset($host['groups']) && (!is_array($host['groups']) || !$host['groups'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('No groups for host "%s".', $dbHosts[$hostId]['host']));
             }
         } else {
             if (!isset($host['groups']) || !is_array($host['groups']) || !$host['groups']) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('No groups for host "%s".', $host['host']));
             }
             foreach ($host['groups'] as $group) {
                 if (!isset($dbGroups[$group['groupid']])) {
                     self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!'));
                 }
             }
         }
     }
     $inventoryFields = getHostInventories();
     $inventoryFields = zbx_objectValues($inventoryFields, 'db_field');
     $hostNames = array();
     foreach ($hosts as &$host) {
         if (isset($host['inventory']) && !empty($host['inventory'])) {
             if (isset($host['inventory_mode']) && $host['inventory_mode'] == HOST_INVENTORY_DISABLED) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set inventory fields for disabled inventory.'));
             }
             $fields = array_keys($host['inventory']);
             foreach ($fields as $field) {
                 if (!in_array($field, $inventoryFields)) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect inventory field "%s".', $field));
                 }
             }
         }
         $updateDiscoveredValidator = new CUpdateDiscoveredValidator(array('allowed' => array('hostid', 'status', 'inventory'), 'messageAllowedField' => _('Cannot update "%1$s" for a discovered host.')));
         if ($update) {
             // cannot update certain fields for discovered hosts
             $this->checkPartialValidator($host, $updateDiscoveredValidator, $dbHosts[$host['hostid']]);
         } else {
             // if visible name is not given or empty it should be set to host name
             if (!isset($host['name']) || zbx_empty(trim($host['name']))) {
                 $host['name'] = $host['host'];
             }
             if (!isset($host['interfaces'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('No interfaces for host "%s".', $host['host']));
             }
         }
         if (isset($host['interfaces'])) {
             if (!is_array($host['interfaces']) || empty($host['interfaces'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('No interfaces for host "%s".', $host['host']));
             }
         }
         if (isset($host['host'])) {
             // Check if host name isn't longer than 64 chars
             if (zbx_strlen($host['host']) > 64) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _n('Maximum host name length is %1$d characters, "%2$s" is %3$d character.', 'Maximum host name length is %1$d characters, "%2$s" is %3$d characters.', 64, $host['host'], zbx_strlen($host['host'])));
             }
             if (!preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/', $host['host'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect characters used for host name "%s".', $host['host']));
             }
             if (isset($hostNames['host'][$host['host']])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate host. Host with the same host name "%s" already exists in data.', $host['host']));
             }
             $hostNames['host'][$host['host']] = $update ? $host['hostid'] : 1;
         }
         if (isset($host['name'])) {
             if ($update) {
                 // if visible name is empty replace it with host name
                 if (zbx_empty(trim($host['name']))) {
                     if (!isset($host['host'])) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Visible name cannot be empty if host name is missing.'));
                     }
                     $host['name'] = $host['host'];
                 }
             }
             // Check if visible name isn't longer than 64 chars
             if (zbx_strlen($host['name']) > 64) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _n('Maximum visible host name length is %1$d characters, "%2$s" is %3$d character.', 'Maximum visible host name length is %1$d characters, "%2$s" is %3$d characters.', 64, $host['name'], zbx_strlen($host['name'])));
             }
             if (isset($hostNames['name'][$host['name']])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate host. Host with the same visible name "%s" already exists in data.', $host['name']));
             }
             $hostNames['name'][$host['name']] = $update ? $host['hostid'] : 1;
         }
     }
     unset($host);
     if ($update || $create) {
         if (isset($hostNames['host']) || isset($hostNames['name'])) {
             $filter = array();
             if (isset($hostNames['host'])) {
                 $filter['host'] = array_keys($hostNames['host']);
             }
             if (isset($hostNames['name'])) {
                 $filter['name'] = array_keys($hostNames['name']);
             }
             $options = array('output' => array('hostid', 'host', 'name'), 'filter' => $filter, 'searchByAny' => true, 'nopermissions' => true, 'preservekeys' => true);
             $hostsExists = $this->get($options);
             foreach ($hostsExists as $hostExists) {
                 if (isset($hostNames['host'][$hostExists['host']])) {
                     if (!$update || bccomp($hostExists['hostid'], $hostNames['host'][$hostExists['host']]) != 0) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same name "%s" already exists.', $hostExists['host']));
                     }
                 }
                 if (isset($hostNames['name'][$hostExists['name']])) {
                     if (!$update || bccomp($hostExists['hostid'], $hostNames['name'][$hostExists['name']]) != 0) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same visible name "%s" already exists.', $hostExists['name']));
                     }
                 }
             }
             $templatesExists = API::Template()->get($options);
             foreach ($templatesExists as $templateExists) {
                 if (isset($hostNames['host'][$templateExists['host']])) {
                     if (!$update || bccomp($templateExists['templateid'], $hostNames['host'][$templateExists['host']]) != 0) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same name "%s" already exists.', $templateExists['host']));
                     }
                 }
                 if (isset($hostNames['name'][$templateExists['name']])) {
                     if (!$update || bccomp($templateExists['templateid'], $hostNames['name'][$templateExists['name']]) != 0) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same visible name "%s" already exists.', $templateExists['name']));
                     }
                 }
             }
         }
     }
     return $update ? $dbHosts : $hosts;
 }
Пример #11
0
 public static function checkValueTypes($table, &$values)
 {
     global $DB;
     $tableSchema = self::getSchema($table);
     foreach ($values as $field => $value) {
         if (!isset($tableSchema['fields'][$field])) {
             unset($values[$field]);
             continue;
         }
         if (is_null($values[$field])) {
             if ($tableSchema['fields'][$field]['null']) {
                 $values[$field] = 'NULL';
             } elseif (isset($tableSchema['fields'][$field]['default'])) {
                 $values[$field] = $tableSchema['fields'][$field]['default'];
             } else {
                 self::exception(self::DBEXECUTE_ERROR, _s('Mandatory field "%1$s" is missing in table "%2$s".', $field, $table));
             }
         }
         if (isset($tableSchema['fields'][$field]['ref_table'])) {
             if ($tableSchema['fields'][$field]['null']) {
                 $values[$field] = zero2null($values[$field]);
             }
         }
         if ($values[$field] === 'NULL') {
             if (!$tableSchema['fields'][$field]['null']) {
                 self::exception(self::DBEXECUTE_ERROR, _s('Incorrect value "NULL" for NOT NULL field "%1$s".', $field));
             }
         } else {
             switch ($tableSchema['fields'][$field]['type']) {
                 case self::FIELD_TYPE_CHAR:
                     $length = zbx_strlen($values[$field]);
                     $values[$field] = zbx_dbstr($values[$field]);
                     if ($length > $tableSchema['fields'][$field]['length']) {
                         self::exception(self::SCHEMA_ERROR, _s('Value "%1$s" is too long for field "%2$s" - %3$d characters. Allowed length is %4$d characters.', $values[$field], $field, $length, $tableSchema['fields'][$field]['length']));
                     }
                     break;
                 case self::FIELD_TYPE_ID:
                 case self::FIELD_TYPE_UINT:
                     if (!zbx_ctype_digit($values[$field])) {
                         self::exception(self::DBEXECUTE_ERROR, _s('Incorrect value "%1$s" for unsigned int field "%2$s".', $values[$field], $field));
                     }
                     $values[$field] = zbx_dbstr($values[$field]);
                     break;
                 case self::FIELD_TYPE_INT:
                     if (!zbx_is_int($values[$field])) {
                         self::exception(self::DBEXECUTE_ERROR, _s('Incorrect value "%1$s" for int field "%2$s".', $values[$field], $field));
                     }
                     $values[$field] = zbx_dbstr($values[$field]);
                     break;
                 case self::FIELD_TYPE_FLOAT:
                     if (!is_numeric($values[$field])) {
                         self::exception(self::DBEXECUTE_ERROR, _s('Incorrect value "%1$s" for float field "%2$s".', $values[$field], $field));
                     }
                     $values[$field] = zbx_dbstr($values[$field]);
                     break;
                 case self::FIELD_TYPE_TEXT:
                     $length = zbx_strlen($values[$field]);
                     $values[$field] = zbx_dbstr($values[$field]);
                     if ($DB['TYPE'] == ZBX_DB_DB2) {
                         if ($length > 2048) {
                             self::exception(self::SCHEMA_ERROR, _s('Value "%1$s" is too long for field "%2$s" - %3$d characters. Allowed length is 2048 characters.', $values[$field], $field, $length));
                         }
                     }
                     break;
             }
         }
     }
 }
Пример #12
0
 /**
  * Validates the "dns" field.
  *
  * @throws APIException if the field is invalid.
  *
  * @param array $interface
  */
 protected function checkDns(array $interface)
 {
     if (zbx_strlen($interface['dns']) > 64) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _n('Maximum DNS name length is %1$d characters, "%2$s" is %3$d character.', 'Maximum DNS name length is %1$d characters, "%2$s" is %3$d characters.', 64, $interface['dns'], zbx_strlen($interface['dns'])));
     }
     if (!empty($interface['dns']) && !preg_match('/^' . ZBX_PREG_DNS_FORMAT . '$/', $interface['dns'])) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect interface DNS parameter "%s" provided.', $interface['dns']));
     }
 }
Пример #13
0
function zbx_str2links($text)
{
    $result = array();
    if (empty($text)) {
        return $result;
    }
    preg_match_all('#https?://[^\\n\\t\\r ]+#u', $text, $matches, PREG_OFFSET_CAPTURE);
    $start = 0;
    foreach ($matches[0] as $match) {
        $result[] = zbx_substr($text, $start, $match[1] - $start);
        $result[] = new CLink($match[0], $match[0], null, null, true);
        $start = $match[1] + zbx_strlen($match[0]);
    }
    $result[] = zbx_substr($text, $start, zbx_strlen($text));
    return $result;
}
Пример #14
0
 public function __construct($url = null)
 {
     $this->url = null;
     $this->port = null;
     $this->host = null;
     $this->protocol = null;
     $this->username = null;
     $this->password = null;
     $this->file = null;
     $this->reference = null;
     $this->path = null;
     $this->query = null;
     $this->arguments = array();
     if (empty($url)) {
         $this->formatArguments();
         $this->url = $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . '?' . $this->getQuery();
     } else {
         $this->url = urldecode($url);
         $tmp_pos = strpos($this->url, '?');
         $this->query = $tmp_pos !== false ? substr($this->url, $tmp_pos + 1) : '';
         $tmp_pos = strpos($this->query, '#');
         if ($tmp_pos !== false) {
             $this->query = zbx_substring($this->query, 0, $tmp_pos);
         }
         $this->formatArguments($this->query);
     }
     $protocolSepIndex = strpos($this->url, '://');
     if ($protocolSepIndex !== false) {
         $this->protocol = strtolower(zbx_substring($this->url, 0, $protocolSepIndex));
         $this->host = substr($this->url, $protocolSepIndex + 3);
         $tmp_pos = strpos($this->host, '/');
         if ($tmp_pos !== false) {
             $this->host = zbx_substring($this->host, 0, $tmp_pos);
         }
         $atIndex = strpos($this->host, '@');
         if ($atIndex !== false) {
             $credentials = zbx_substring($this->host, 0, $atIndex);
             $colonIndex = strpos(credentials, ':');
             if ($colonIndex !== false) {
                 $this->username = zbx_substring($credentials, 0, $colonIndex);
                 $this->password = substr($credentials, $colonIndex);
             } else {
                 $this->username = $credentials;
             }
             $this->host = substr($this->host, $atIndex + 1);
         }
         $host_ipv6 = strpos($this->host, ']');
         if ($host_ipv6 !== false) {
             if ($host_ipv6 < zbx_strlen($this->host) - 1) {
                 $host_ipv6++;
                 $host_less = substr($this->host, $host_ipv6);
                 $portColonIndex = strpos($host_less, ':');
                 if ($portColonIndex !== false) {
                     $this->host = zbx_substring($this->host, 0, $host_ipv6);
                     $this->port = substr($host_less, $portColonIndex + 1);
                 }
             }
         } else {
             $portColonIndex = strpos($this->host, ':');
             if ($portColonIndex !== false) {
                 $this->host = zbx_substring($this->host, 0, $portColonIndex);
                 $this->port = substr($this->host, $portColonIndex + 1);
             }
         }
         $this->file = substr($this->url, $protocolSepIndex + 3);
         $this->file = substr($this->file, strpos($this->file, '/'));
         if ($this->file == $this->host) {
             $this->file = '';
         }
     } else {
         $this->file = $this->url;
     }
     $tmp_pos = strpos($this->file, '?');
     if ($tmp_pos !== false) {
         $this->file = zbx_substring($this->file, 0, $tmp_pos);
     }
     $refSepIndex = strpos($url, '#');
     if ($refSepIndex !== false) {
         $this->file = zbx_substring($this->file, 0, $refSepIndex);
         $this->reference = substr($url, strpos($url, '#') + 1);
     }
     $this->path = $this->file;
     if (zbx_strlen($this->query) > 0) {
         $this->file .= '?' . $this->query;
     }
     if (zbx_strlen($this->reference) > 0) {
         $this->file .= '#' . $this->reference;
     }
     if (isset($_COOKIE['zbx_sessionid'])) {
         $this->setArgument('sid', substr($_COOKIE['zbx_sessionid'], 16, 16));
     }
 }
    foreach ($expressions as $exprPart) {
        if (isset($macrosData[$exprPart['expression']])) {
            continue;
        }
        $fname = 'test_data_' . md5($exprPart['expression']);
        $macrosData[$exprPart['expression']] = get_request($fname, '');
        $info = get_item_function_info($exprPart['expression']);
        if (!is_array($info) && isset($definedErrorPhrases[$info])) {
            $allowedTesting = false;
            $control = new CTextBox($fname, $macrosData[$exprPart['expression']], 30);
            $control->setAttribute('disabled', 'disabled');
        } else {
            $octet = $info['value_type'] == 'HHMMSS';
            $validation = $info['validation'];
            if (substr($validation, 0, COMBO_PATTERN_LENGTH) == COMBO_PATTERN) {
                $vals = explode(',', substr($validation, COMBO_PATTERN_LENGTH, zbx_strlen($validation) - COMBO_PATTERN_LENGTH - 4));
                $control = new CComboBox($fname, $macrosData[$exprPart['expression']]);
                foreach ($vals as $v) {
                    $control->addItem($v, $v);
                }
            } else {
                $control = new CTextBox($fname, $macrosData[$exprPart['expression']], 30);
            }
            $fields[$fname] = array($info['type'], O_OPT, null, $validation, 'isset({test_expression})', $exprPart['expression']);
        }
        $data_table->addRow(new CRow(array($exprPart['expression'], is_array($info) || !isset($definedErrorPhrases[$info]) ? $info['value_type'] : new CCol($definedErrorPhrases[$info], 'disaster'), $control)));
    }
}
//---------------------------------- CHECKS ------------------------------------
$fields['test_expression'] = array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, null);
if (!check_fields($fields)) {
Пример #16
0
function explode_exp($expression, $html = false, $resolve_macro = false, $src_host = null, $dst_host = null)
{
    $exp = !$html ? '' : array();
    $trigger = array();
    for ($i = 0, $state = '', $max = zbx_strlen($expression); $i < $max; $i++) {
        if ($expression[$i] == '{') {
            if ($expression[$i + 1] == '$') {
                $usermacro = '';
                $state = 'USERMACRO';
            } elseif ($expression[$i + 1] == '#') {
                $lldmacro = '';
                $state = 'LLDMACRO';
            } else {
                $functionid = '';
                $state = 'FUNCTIONID';
                continue;
            }
        } elseif ($expression[$i] == '}') {
            if ($state == 'USERMACRO') {
                $usermacro .= '}';
                if ($resolve_macro) {
                    $function_data['expression'] = $usermacro;
                    $function_data = API::UserMacro()->resolveTrigger($function_data);
                    $usermacro = $function_data['expression'];
                }
                if ($html) {
                    array_push($exp, $usermacro);
                } else {
                    $exp .= $usermacro;
                }
                $state = '';
                continue;
            } elseif ($state == 'LLDMACRO') {
                $lldmacro .= '}';
                if ($html) {
                    array_push($exp, $lldmacro);
                } else {
                    $exp .= $lldmacro;
                }
                $state = '';
                continue;
            } elseif ($functionid == 'TRIGGER.VALUE') {
                if ($html) {
                    array_push($exp, '{' . $functionid . '}');
                } else {
                    $exp .= '{' . $functionid . '}';
                }
                $state = '';
                continue;
            }
            $sql = 'SELECT h.host,i.itemid,i.key_,f.function,f.triggerid,f.parameter,i.itemid,i.status,i.type,i.flags' . ' FROM items i,functions f,hosts h' . ' WHERE f.functionid=' . $functionid . ' AND i.itemid=f.itemid' . ' AND h.hostid=i.hostid';
            if (is_numeric($functionid) && ($function_data = DBfetch(DBselect($sql)))) {
                if ($resolve_macro) {
                    $trigger = $function_data;
                    $function_data = API::UserMacro()->resolveItem($function_data);
                    $function_data['expression'] = $function_data['parameter'];
                    $function_data = API::UserMacro()->resolveTrigger($function_data);
                    $function_data['parameter'] = $function_data['expression'];
                }
                if (!is_null($src_host) && !is_null($dst_host) && strcmp($src_host, $function_data['host']) == 0) {
                    $function_data['host'] = $dst_host;
                }
                if ($html) {
                    $style = $function_data['status'] == ITEM_STATUS_DISABLED ? 'disabled' : 'unknown';
                    if ($function_data['status'] == ITEM_STATUS_ACTIVE) {
                        $style = 'enabled';
                    }
                    if ($function_data['flags'] == ZBX_FLAG_DISCOVERY_CREATED || $function_data['type'] == ITEM_TYPE_HTTPTEST) {
                        $link = new CSpan($function_data['host'] . ':' . $function_data['key_'], $style);
                    } elseif ($function_data['flags'] == ZBX_FLAG_DISCOVERY_PROTOTYPE) {
                        $link = new CLink($function_data['host'] . ':' . $function_data['key_'], 'disc_prototypes.php?form=update&itemid=' . $function_data['itemid'] . '&parent_discoveryid=' . $trigger['discoveryRuleid'] . '&switch_node=' . id2nodeid($function_data['itemid']), $style);
                    } else {
                        $link = new CLink($function_data['host'] . ':' . $function_data['key_'], 'items.php?form=update&itemid=' . $function_data['itemid'] . '&switch_node=' . id2nodeid($function_data['itemid']), $style);
                    }
                    array_push($exp, array('{', $link, '.', bold($function_data['function'] . '('), $function_data['parameter'], bold(')'), '}'));
                } else {
                    $exp .= '{' . $function_data['host'] . ':' . $function_data['key_'] . '.' . $function_data['function'] . '(' . $function_data['parameter'] . ')}';
                }
            } else {
                if ($html) {
                    array_push($exp, new CSpan('*ERROR*', 'on'));
                } else {
                    $exp .= '*ERROR*';
                }
            }
            $state = '';
            continue;
        }
        switch ($state) {
            case 'FUNCTIONID':
                $functionid .= $expression[$i];
                break;
            case 'USERMACRO':
                $usermacro .= $expression[$i];
                break;
            case 'LLDMACRO':
                $lldmacro .= $expression[$i];
                break;
            default:
                if ($html) {
                    array_push($exp, $expression[$i]);
                } else {
                    $exp .= $expression[$i];
                }
        }
    }
    return $exp;
}
    if (!isset($step['url'])) {
        $step['url'] = '';
    }
    if (!isset($step['posts'])) {
        $step['posts'] = '';
    }
    if (!isset($step['required'])) {
        $step['required'] = '';
    }
    $numSpan = new CSpan($i++ . ':');
    $numSpan->addClass('rowNum');
    $numSpan->setAttribute('id', 'current_step_' . $stepid);
    $name = new CSpan($step['name'], 'link');
    $name->setAttributes(array('id' => 'name_' . $stepid, 'name_step' => $stepid));
    if (zbx_strlen($step['url']) > 70) {
        $url = new CSpan(substr($step['url'], 0, 35) . SPACE . '...' . SPACE . substr($step['url'], zbx_strlen($step['url']) - 25, 25));
        $url->setHint($step['url']);
    } else {
        $url = $step['url'];
    }
    if ($this->data['templated']) {
        $removeButton = SPACE;
        $dragHandler = SPACE;
    } else {
        $removeButton = new CButton('remove_' . $stepid, _('Remove'), 'javascript: removeStep(this);', 'link_menu');
        $removeButton->setAttribute('remove_step', $stepid);
        $dragHandler = new CSpan(null, 'ui-icon ui-icon-arrowthick-2-n-s move');
    }
    $row = new CRow(array($dragHandler, $numSpan, $name, $step['timeout'] . SPACE . _('sec'), $url, htmlspecialchars($step['required']), $step['status_codes'], $removeButton), 'sortable', 'steps_' . $stepid);
    $stepsTable->addRow($row);
}
Пример #18
0
$darkgreen = imagecolorallocate($im, 0, 150, 0);
$bluei = imagecolorallocate($im, 0, 0, 255);
$darkblue = imagecolorallocate($im, 0, 0, 150);
$yellow = imagecolorallocate($im, 255, 255, 0);
$darkyellow = imagecolorallocate($im, 150, 150, 0);
$cyan = imagecolorallocate($im, 0, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$gray = imagecolorallocate($im, 150, 150, 150);
$white = imagecolorallocate($im, 255, 255, 255);
$bg = imagecolorallocate($im, 6 + 6 * 16, 7 + 7 * 16, 8 + 8 * 16);
$x = imagesx($im);
$y = imagesy($im);
imagefilledrectangle($im, 0, 0, $x, $y, $white);
imagerectangle($im, 0, 0, $x - 1, $y - 1, $black);
$str = _s('%1$s (year %2$s)', $dbTrigger['description'], zbx_date2str('Y'));
$x = imagesx($im) / 2 - imagefontwidth(4) * zbx_strlen($str) / 2;
imageText($im, 10, 0, $x, 14, $darkred, $str);
$now = time(null);
$count_now = array();
$true = array();
$false = array();
$start = mktime(0, 0, 0, 1, 1, date('Y'));
$wday = date('w', $start);
if ($wday == 0) {
    $wday = 7;
}
$start = $start - ($wday - 1) * SEC_PER_DAY;
$weeks = (int) (date('z') / 7 + 1);
for ($i = 0; $i < $weeks; $i++) {
    $period_start = $start + SEC_PER_WEEK * $i;
    $period_end = $start + SEC_PER_WEEK * ($i + 1);
Пример #19
0
 private function makeSImgStr($id)
 {
     $tr = new CRow();
     $count = isset($this->tree[$id]['nodeimg']) ? zbx_strlen($this->tree[$id]['nodeimg']) : 0;
     for ($i = 0; $i < $count; $i++) {
         $td = new CCol();
         switch ($this->tree[$id]['nodeimg'][$i]) {
             case 'O':
                 $td->setAttribute('style', 'width: 22px');
                 $img = new CImg('images/general/tree/zero.gif', 'o', '22', '14');
                 break;
             case 'I':
                 $td->setAttribute('style', 'width:22px; background-image:url(images/general/tree/pointc.gif);');
                 $img = new CImg('images/general/tree/zero.gif', 'i', '22', '14');
                 break;
             case 'L':
                 $td->setAttribute('valign', 'top');
                 $div = new CTag('div', 'yes');
                 $div->setAttribute('style', 'height: 10px; width:22px; margin-left: -3px; background-image:url(images/general/tree/pointc.gif);');
                 if ($this->tree[$id]['nodetype'] == 2) {
                     $img = new CImg('images/general/tree/plus.gif', 'y', '22', '14');
                     $img->setAttribute('onclick', $this->treename . '.closeSNodeX("' . $id . '",this);');
                     $img->setAttribute('id', 'idi_' . $id);
                     $img->setAttribute('class', 'pointer');
                 } else {
                     $img = new CImg('images/general/tree/pointl.gif', 'y', '22', '14');
                 }
                 $div->addItem($img);
                 $img = $div;
                 break;
             case 'T':
                 $td->setAttribute('valign', 'top');
                 if ($this->tree[$id]['nodetype'] == 2) {
                     $td->setAttribute('style', 'width:22px; background-image:url(images/general/tree/pointc.gif);');
                     $img = new CImg('images/general/tree/plus.gif', 't', '22', '14');
                     $img->setAttribute('onclick', $this->treename . '.closeSNodeX("' . $id . '",this);');
                     $img->setAttribute('id', 'idi_' . $id);
                     $img->setAttribute('class', 'pointer');
                     $img->setAttribute('style', 'top:2px;left:-3px;position:relative;');
                 } else {
                     $td->setAttribute('style', 'width:22px; background-image:url(images/general/tree/pointc.gif);');
                     $img = new CImg('images/general/tree/pointl.gif', 't', '22', '14');
                 }
                 break;
         }
         $td->addItem($img);
         $tr->addItem($td);
     }
     return $tr;
 }
Пример #20
0
 public function setSeriesLegend($seriesLegend)
 {
     foreach ($seriesLegend as $key => $value) {
         $this->seriesLegend[$key] = $value;
         $tmp = zbx_strlen($value) * 7 + 8;
         // count of chars * font size + color box
         if ($tmp > $this->shiftlegendright) {
             $this->shiftlegendright = $tmp;
         }
     }
 }
Пример #21
0
function zbx_substring($haystack, $start, $end = null)
{
    if ($end < $start) {
        return '';
    }
    $len = zbx_strlen($haystack);
    if (is_null($end)) {
        $result = substr($haystack, $start);
    } else {
        $result = substr($haystack, $start, $end - $start);
    }
    return $result;
}
Пример #22
0
 /**
  * The isValid method takes a UTF-16 encoded string and determines if it is
  * a syntactically correct JSON text.
  *
  * It is implemented as a Pushdown Automaton; that means it is a finite
  * state machine with a stack.
  *
  * @param string $str The JSON text to validate
  * @return bool
  */
 public function isValid($str)
 {
     $len = zbx_strlen($str);
     $_the_state = 0;
     $this->_the_top = -1;
     $this->_push(self::MODE_DONE);
     for ($_the_index = 0; $_the_index < $len; $_the_index++) {
         $b = $str[$_the_index];
         if (chr(ord($b) & 127) == $b) {
             $c = $this->_ascii_class[ord($b)];
             if ($c <= self::S_ERR) {
                 return false;
             }
         } else {
             $c = self::S_ETC;
         }
         // get the next state from the transition table
         $s = $this->_state_transition_table[$_the_state][$c];
         if ($s < 0) {
             // perform one of the predefined actions
             switch ($s) {
                 // empty }
                 case -9:
                     if (!$this->_pop(self::MODE_KEY)) {
                         return false;
                     }
                     $_the_state = 9;
                     break;
                     // {
                 // {
                 case -8:
                     if (!$this->_push(self::MODE_KEY)) {
                         return false;
                     }
                     $_the_state = 1;
                     break;
                     // }
                 // }
                 case -7:
                     if (!$this->_pop(self::MODE_OBJECT)) {
                         return false;
                     }
                     $_the_state = 9;
                     break;
                     // [
                 // [
                 case -6:
                     if (!$this->_push(self::MODE_ARRAY)) {
                         return false;
                     }
                     $_the_state = 2;
                     break;
                     // ]
                 // ]
                 case -5:
                     if (!$this->_pop(self::MODE_ARRAY)) {
                         return false;
                     }
                     $_the_state = 9;
                     break;
                     // "
                 // "
                 case -4:
                     switch ($this->_the_stack[$this->_the_top]) {
                         case self::MODE_KEY:
                             $_the_state = 27;
                             break;
                         case self::MODE_ARRAY:
                         case self::MODE_OBJECT:
                             $_the_state = 9;
                             break;
                         default:
                             return false;
                     }
                     break;
                     // '
                 // '
                 case -3:
                     switch ($this->_the_stack[$this->_the_top]) {
                         case self::MODE_OBJECT:
                             if ($this->_pop(self::MODE_OBJECT) && $this->_push(self::MODE_KEY)) {
                                 $_the_state = 29;
                             }
                             break;
                         case self::MODE_ARRAY:
                             $_the_state = 28;
                             break;
                         default:
                             return false;
                     }
                     break;
                     // :
                 // :
                 case -2:
                     if ($this->_pop(self::MODE_KEY) && $this->_push(self::MODE_OBJECT)) {
                         $_the_state = 28;
                         break;
                     }
                     // syntax error
                 // syntax error
                 case -1:
                     return false;
             }
         } else {
             // change the state and iterate
             $_the_state = $s;
         }
     }
     if ($_the_state == 9 && $this->_pop(self::MODE_DONE)) {
         return true;
     }
     return false;
 }
Пример #23
0
function show_messages($bool = true, $okmsg = null, $errmsg = null)
{
    global $page, $ZBX_MESSAGES;
    if (!defined('PAGE_HEADER_LOADED')) {
        return null;
    }
    if (defined('ZBX_API_REQUEST')) {
        return null;
    }
    if (!isset($page['type'])) {
        $page['type'] = PAGE_TYPE_HTML;
    }
    $message = array();
    $width = 0;
    $height = 0;
    if (!$bool && !is_null($errmsg)) {
        $msg = _('ERROR') . ': ' . $errmsg;
    } elseif ($bool && !is_null($okmsg)) {
        $msg = $okmsg;
    }
    if (isset($msg)) {
        switch ($page['type']) {
            case PAGE_TYPE_IMAGE:
                array_push($message, array('text' => $msg, 'color' => !$bool ? array('R' => 255, 'G' => 0, 'B' => 0) : array('R' => 34, 'G' => 51, 'B' => 68), 'font' => 2));
                $width = max($width, imagefontwidth(2) * zbx_strlen($msg) + 1);
                $height += imagefontheight(2) + 1;
                break;
            case PAGE_TYPE_XML:
                echo htmlspecialchars($msg) . "\n";
                break;
            case PAGE_TYPE_HTML:
            default:
                $msg_tab = new CTable($msg, $bool ? 'msgok' : 'msgerr');
                $msg_tab->setCellPadding(0);
                $msg_tab->setCellSpacing(0);
                $row = array();
                $msg_col = new CCol(bold($msg), 'msg_main msg');
                $msg_col->setAttribute('id', 'page_msg');
                $row[] = $msg_col;
                if (isset($ZBX_MESSAGES) && !empty($ZBX_MESSAGES)) {
                    $msg_details = new CDiv(_('Details'), 'blacklink');
                    $msg_details->setAttribute('onclick', 'javascript: showHide("msg_messages", IE ? "block" : "table");');
                    $msg_details->setAttribute('title', _('Maximize') . '/' . _('Minimize'));
                    array_unshift($row, new CCol($msg_details, 'clr'));
                }
                $msg_tab->addRow($row);
                $msg_tab->show();
                break;
        }
    }
    if (isset($ZBX_MESSAGES) && !empty($ZBX_MESSAGES)) {
        if ($page['type'] == PAGE_TYPE_IMAGE) {
            $msg_font = 2;
            foreach ($ZBX_MESSAGES as $msg) {
                if ($msg['type'] == 'error') {
                    array_push($message, array('text' => $msg['message'], 'color' => array('R' => 255, 'G' => 55, 'B' => 55), 'font' => $msg_font));
                } else {
                    array_push($message, array('text' => $msg['message'], 'color' => array('R' => 155, 'G' => 155, 'B' => 55), 'font' => $msg_font));
                }
                $width = max($width, imagefontwidth($msg_font) * zbx_strlen($msg['message']) + 1);
                $height += imagefontheight($msg_font) + 1;
            }
        } elseif ($page['type'] == PAGE_TYPE_XML) {
            foreach ($ZBX_MESSAGES as $msg) {
                echo '[' . $msg['type'] . '] ' . $msg['message'] . "\n";
            }
        } else {
            $lst_error = new CList(null, 'messages');
            foreach ($ZBX_MESSAGES as $msg) {
                $lst_error->addItem($msg['message'], $msg['type']);
                $bool = $bool && 'error' != zbx_strtolower($msg['type']);
            }
            $msg_show = 6;
            $msg_count = count($ZBX_MESSAGES);
            if ($msg_count > $msg_show) {
                $msg_count = $msg_show * 16;
                $lst_error->setAttribute('style', 'height: ' . $msg_count . 'px;');
            }
            $tab = new CTable(null, $bool ? 'msgok' : 'msgerr');
            $tab->setCellPadding(0);
            $tab->setCellSpacing(0);
            $tab->setAttribute('id', 'msg_messages');
            $tab->setAttribute('style', 'width: 100%;');
            if (isset($msg_tab) && $bool) {
                $tab->setAttribute('style', 'display: none;');
            }
            $tab->addRow(new CCol($lst_error, 'msg'));
            $tab->show();
        }
        $ZBX_MESSAGES = null;
    }
    if ($page['type'] == PAGE_TYPE_IMAGE && count($message) > 0) {
        $width += 2;
        $height += 2;
        $canvas = imagecreate($width, $height);
        imagefilledrectangle($canvas, 0, 0, $width, $height, imagecolorallocate($canvas, 255, 255, 255));
        foreach ($message as $id => $msg) {
            $message[$id]['y'] = 1 + (isset($previd) ? $message[$previd]['y'] + $message[$previd]['h'] : 0);
            $message[$id]['h'] = imagefontheight($msg['font']);
            imagestring($canvas, $msg['font'], 1, $message[$id]['y'], $msg['text'], imagecolorallocate($canvas, $msg['color']['R'], $msg['color']['G'], $msg['color']['B']));
            $previd = $id;
        }
        imageOut($canvas);
        imagedestroy($canvas);
    }
}
Пример #24
0
/**
 * Format item lastvalue depending on it's value type.
 *
 * @param array $item
 *
 * @return string
 */
function formatItemValueType(array $item)
{
    if ($item['value_type'] == ITEM_VALUE_TYPE_FLOAT || $item['value_type'] == ITEM_VALUE_TYPE_UINT64) {
        $value = convert_units($item['lastvalue'], $item['units']);
    } elseif ($item['value_type'] == ITEM_VALUE_TYPE_STR || $item['value_type'] == ITEM_VALUE_TYPE_TEXT || $item['value_type'] == ITEM_VALUE_TYPE_LOG) {
        $value = $item['lastvalue'];
        if (zbx_strlen($value) > 20) {
            $value = zbx_substr($value, 0, 20) . ' ...';
        }
    } else {
        $value = _('Unknown value type');
    }
    return $value;
}
Пример #25
0
 private static function checkValueType($value, $type)
 {
     switch ($type) {
         case PROFILE_TYPE_ID:
             return zbx_ctype_digit($value);
         case PROFILE_TYPE_INT:
             return zbx_is_int($value);
         case PROFILE_TYPE_STR:
             return zbx_strlen($value) <= self::$stringProfileMaxLength;
         default:
             return true;
     }
 }
Пример #26
0
function check_type(&$field, $flags, &$var, $type)
{
    if (is_array($var) && $type != T_ZBX_IP) {
        $err = ZBX_VALID_OK;
        foreach ($var as $el) {
            $err |= check_type($field, $flags, $el, $type);
        }
        return $err;
    }
    if ($type == T_ZBX_IP) {
        if (!validate_ip($var, $arr)) {
            if ($flags & P_SYS) {
                info("Critical error. Field [" . $field . "] is not IP");
                return ZBX_VALID_ERROR;
            } else {
                info("Warning. Field [" . $field . "] is not IP");
                return ZBX_VALID_WARNING;
            }
        }
        return ZBX_VALID_OK;
    }
    if ($type == T_ZBX_IP_RANGE) {
        if (!validate_ip_range($var)) {
            if ($flags & P_SYS) {
                info("Critical error. Field [" . $field . "] is not IP range");
                return ZBX_VALID_ERROR;
            } else {
                info("Warning. Field [" . $field . "] is not IP range");
                return ZBX_VALID_WARNING;
            }
        }
        return ZBX_VALID_OK;
    }
    if ($type == T_ZBX_PORTS) {
        $err = ZBX_VALID_OK;
        foreach (explode(',', $var) as $el) {
            foreach (explode('-', $el) as $p) {
                $err |= check_type($field, $flags, $p, T_ZBX_INT);
            }
        }
        return $err;
    }
    if ($type == T_ZBX_INT_RANGE) {
        if (!is_int_range($var)) {
            if ($flags & P_SYS) {
                info("Critical error. Field [" . $field . "] is not integer range");
                return ZBX_VALID_ERROR;
            } else {
                info("Warning. Field [" . $field . "] is not integer range");
                return ZBX_VALID_WARNING;
            }
        }
        return ZBX_VALID_OK;
    }
    if ($type == T_ZBX_INT && !is_numeric($var)) {
        if ($flags & P_SYS) {
            info("Critical error. Field [" . $field . "] is not integer");
            return ZBX_VALID_ERROR;
        } else {
            info("Warning. Field [" . $field . "] is not integer");
            return ZBX_VALID_WARNING;
        }
    }
    if ($type == T_ZBX_DBL && !is_numeric($var)) {
        if ($flags & P_SYS) {
            info("Critical error. Field [" . $field . "] is not double");
            return ZBX_VALID_ERROR;
        } else {
            info("Warning. Field [" . $field . "] is not double");
            return ZBX_VALID_WARNING;
        }
    }
    if ($type == T_ZBX_STR && !is_string($var)) {
        if ($flags & P_SYS) {
            info("Critical error. Field [" . $field . "] is not string");
            return ZBX_VALID_ERROR;
        } else {
            info("Warning. Field [" . $field . "] is not string");
            return ZBX_VALID_WARNING;
        }
    }
    //*
    if ($type == T_ZBX_STR && !defined('ZBX_ALLOW_UNICODE') && strlen($var) != zbx_strlen($var)) {
        if ($flags & P_SYS) {
            info("Critical error. Field [" . $field . "] contains Multibyte chars");
            return ZBX_VALID_ERROR;
        } else {
            info("Warning. Field [" . $field . "] - multibyte chars are restricted");
            return ZBX_VALID_ERROR;
        }
    }
    //*/
    if ($type == T_ZBX_CLR && !is_hex_color($var)) {
        $var = 'FFFFFF';
        if ($flags & P_SYS) {
            info("Critical error. Field [" . $field . "] is not a colour");
            return ZBX_VALID_ERROR;
        } else {
            info("Warning. Field [" . $field . "] is not a colour");
            return ZBX_VALID_WARNING;
        }
    }
    return ZBX_VALID_OK;
}
 protected function drawLegend()
 {
     $shiftY = $this->shiftY + $this->shiftYLegend;
     $max_host_len = 0;
     $max_name_len = 0;
     for ($i = 0; $i < $this->num; $i++) {
         if (zbx_strlen($this->items[$i]['host']) > $max_host_len) {
             $max_host_len = zbx_strlen($this->items[$i]['host']);
         }
         if (zbx_strlen($this->items[$i]['name']) > $max_name_len) {
             $max_name_len = zbx_strlen($this->items[$i]['name']);
         }
     }
     for ($i = 0; $i < $this->num; $i++) {
         $color = $this->getColor($this->items[$i]['color'], 0);
         $data =& $this->data[$this->items[$i]['itemid']][$this->items[$i]['calc_type']];
         switch ($this->items[$i]['calc_fnc']) {
             case CALC_FNC_MIN:
                 $fnc_name = 'min';
                 $datavalue = $data->min;
                 break;
             case CALC_FNC_MAX:
                 $fnc_name = 'max';
                 $datavalue = $data->max;
                 break;
             case CALC_FNC_LST:
                 $fnc_name = 'last';
                 $datavalue = $data->lst;
                 break;
             case CALC_FNC_AVG:
             default:
                 $fnc_name = 'avg';
                 $datavalue = $data->avg;
         }
         $proc = $datavalue * 100 / $this->sum;
         if (isset($data) && isset($datavalue)) {
             $strvalue = sprintf(_('Value') . ': %s (' . (round($proc) != $proc ? '%0.2f' : '%s') . '%%)', convert_units($datavalue, $this->items[$i]['units']), $proc);
             $str = sprintf('%s: %s [%s] ', str_pad($this->items[$i]['host'], $max_host_len, ' '), str_pad($this->items[$i]['name'], $max_name_len, ' '), $fnc_name);
         } else {
             $strvalue = sprintf(_('Value: no data'));
             $str = sprintf('%s: %s [ ' . _('no data') . ' ]', str_pad($this->items[$i]['host'], $max_host_len, ' '), str_pad($this->items[$i]['name'], $max_name_len, ' '));
         }
         imagefilledrectangle($this->im, $this->shiftXleft, $this->sizeY + $shiftY + 14 * $i - 5, $this->shiftXleft + 10, $this->sizeY + $shiftY + 5 + 14 * $i, $color);
         imagerectangle($this->im, $this->shiftXleft, $this->sizeY + $shiftY + 14 * $i - 5, $this->shiftXleft + 10, $this->sizeY + $shiftY + 5 + 14 * $i, $this->getColor('Black No Alpha'));
         imageText($this->im, 8, 0, $this->shiftXleft + 15, $this->sizeY + $shiftY + 14 * $i + 5, $this->getColor($this->graphtheme['textcolor'], 0), $str);
         $shiftX = $this->fullSizeX - $this->shiftlegendright - $this->shiftXright + 25;
         imagefilledrectangle($this->im, $shiftX - 10, $this->shiftY + 10 + 14 * $i, $shiftX, $this->shiftY + 10 + 10 + 14 * $i, $color);
         imagerectangle($this->im, $shiftX - 10, $this->shiftY + 10 + 14 * $i, $shiftX, $this->shiftY + 10 + 10 + 14 * $i, $this->GetColor('Black No Alpha'));
         imagetext($this->im, 8, 0, $shiftX + 5, $this->shiftY + 10 + 14 * $i + 10, $this->getColor($this->graphtheme['textcolor'], 0), $strvalue);
     }
     if ($this->sizeY < 120) {
         return;
     }
 }
function imageTextSize($fontsize, $angle, $string)
{
    $gdinfo = gd_info();
    $result = array();
    if ($gdinfo['FreeType Support'] && function_exists('imagettfbbox')) {
        if (preg_match(ZBX_PREG_DEF_FONT_STRING, $string) && $angle != 0) {
            $ttf = ZBX_FONTPATH . '/' . ZBX_FONT_NAME . '.ttf';
        } else {
            $ttf = ZBX_FONTPATH . '/' . ZBX_GRAPH_FONT_NAME . '.ttf';
        }
        $ar = imagettfbbox($fontsize, $angle, $ttf, $string);
        $result['height'] = abs($ar[1] - $ar[5]);
        $result['width'] = abs($ar[0] - $ar[4]);
        $result['baseline'] = $ar[1];
    } else {
        switch ($fontsize) {
            case 5:
                $fontsize = 1;
                break;
            case 6:
                $fontsize = 1;
                break;
            case 7:
                $fontsize = 2;
                break;
            case 8:
                $fontsize = 2;
                break;
            case 9:
                $fontsize = 3;
                break;
            case 10:
                $fontsize = 3;
                break;
            case 11:
                $fontsize = 4;
                break;
            case 12:
                $fontsize = 4;
                break;
            case 13:
                $fontsize = 5;
                break;
            case 14:
                $fontsize = 5;
                break;
            default:
                $fontsize = 2;
                break;
        }
        if ($angle) {
            $result['width'] = imagefontheight($fontsize);
            $result['height'] = imagefontwidth($fontsize) * zbx_strlen($string);
        } else {
            $result['height'] = imagefontheight($fontsize);
            $result['width'] = imagefontwidth($fontsize) * zbx_strlen($string);
        }
        $result['baseline'] = 0;
    }
    return $result;
}
Пример #29
0
 /**
  * Add Host
  *
  * @param _array $hosts multidimensional array with Hosts data
  * @param string $hosts['host'] Host name.
  * @param array $hosts['groups'] array of HostGroup objects with IDs add Host to.
  * @param int $hosts['port'] Port. OPTIONAL
  * @param int $hosts['status'] Host Status. OPTIONAL
  * @param int $hosts['useip'] Use IP. OPTIONAL
  * @param string $hosts['dns'] DNS. OPTIONAL
  * @param string $hosts['ip'] IP. OPTIONAL
  * @param int $hosts['proxy_hostid'] Proxy Host ID. OPTIONAL
  * @param int $hosts['useipmi'] Use IPMI. OPTIONAL
  * @param string $hosts['ipmi_ip'] IPMAI IP. OPTIONAL
  * @param int $hosts['ipmi_port'] IPMI port. OPTIONAL
  * @param int $hosts['ipmi_authtype'] IPMI authentication type. OPTIONAL
  * @param int $hosts['ipmi_privilege'] IPMI privilege. OPTIONAL
  * @param string $hosts['ipmi_username'] IPMI username. OPTIONAL
  * @param string $hosts['ipmi_password'] IPMI password. OPTIONAL
  * @return boolean
  */
 public static function create($hosts)
 {
     $hosts = zbx_toArray($hosts);
     $hostids = array();
     $groupids = array();
     try {
         self::BeginTransaction(__METHOD__);
         // BASIC VALIDATION {{{
         foreach ($hosts as $hnum => $host) {
             // CHECK IF HOSTS HAVE AT LEAST 1 GROUP
             if (empty($host['groups'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, sprintf(S_NO_GROUPS_FOR_HOST, $host['host']));
             }
             // Check if host name isn't longer then 64 chars
             if (zbx_strlen($host['host']) > 64) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, sprintf(S_HOST_NAME_MUST_BE_LONGER, 64, $host['host'], zbx_strlen($host['host'])));
             }
             $hosts[$hnum]['groups'] = zbx_toArray($hosts[$hnum]['groups']);
             foreach ($hosts[$hnum]['groups'] as $gnum => $group) {
                 $groupids[$group['groupid']] = $group['groupid'];
             }
         }
         // }}}
         // PERMISSIONS {{{
         $upd_groups = CHostGroup::get(array('groupids' => $groupids, 'editable' => 1, 'preservekeys' => 1));
         foreach ($groupids as $gnum => $groupid) {
             if (!isset($upd_groups[$groupid])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSIONS);
             }
         }
         // }}} PERMISSIONS
         foreach ($hosts as $num => $host) {
             $host_db_fields = array('host' => null, 'port' => 0, 'status' => 0, 'useip' => 0, 'dns' => '', 'ip' => '0.0.0.0', 'proxy_hostid' => 0, 'useipmi' => 0, 'ipmi_ip' => '', 'ipmi_port' => 623, 'ipmi_authtype' => 0, 'ipmi_privilege' => 0, 'ipmi_username' => '', 'ipmi_password' => '');
             if (!check_db_fields($host_db_fields, $host)) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, 'Wrong fields for host [ ' . $host['host'] . ' ]');
             }
             if (!preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/i', $host['host'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for Hostname [ ' . $host['host'] . ' ]');
             }
             if (!empty($host['dns']) && !preg_match('/^' . ZBX_PREG_DNS_FORMAT . '$/i', $host['dns'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for DNS [ ' . $host['dns'] . ' ]');
             }
             if (self::exists(array('host' => $host['host']))) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_HOST . ' [ ' . $host['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL);
             }
             if (CTemplate::exists(array('host' => $host['host']))) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_TEMPLATE . ' [ ' . $host['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL);
             }
             $hostid = get_dbid('hosts', 'hostid');
             $hostids[] = $hostid;
             $result = DBexecute('INSERT INTO hosts (hostid, proxy_hostid, host, port, status, useip, dns, ip, disable_until, available,' . 'useipmi,ipmi_port,ipmi_authtype,ipmi_privilege,ipmi_username,ipmi_password,ipmi_ip) VALUES (' . $hostid . ',' . $host['proxy_hostid'] . ',' . zbx_dbstr($host['host']) . ',' . $host['port'] . ',' . $host['status'] . ',' . $host['useip'] . ',' . zbx_dbstr($host['dns']) . ',' . zbx_dbstr($host['ip']) . ',0,' . HOST_AVAILABLE_UNKNOWN . ',' . $host['useipmi'] . ',' . $host['ipmi_port'] . ',' . $host['ipmi_authtype'] . ',' . $host['ipmi_privilege'] . ',' . zbx_dbstr($host['ipmi_username']) . ',' . zbx_dbstr($host['ipmi_password']) . ',' . zbx_dbstr($host['ipmi_ip']) . ')');
             if (!$result) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror');
             }
             foreach ($host['groups'] as $group) {
                 $hostgroupid = get_dbid('hosts_groups', 'hostgroupid');
                 $result = DBexecute("INSERT INTO hosts_groups (hostgroupid, hostid, groupid) VALUES ({$hostgroupid}, {$hostid}, {$group['groupid']})");
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror');
                 }
             }
             $host['hostid'] = $hostid;
             $options = array();
             $options['hosts'] = $host;
             if (isset($host['templates']) && !is_null($host['templates'])) {
                 $options['templates'] = $host['templates'];
             }
             if (isset($host['macros']) && !is_null($host['macros'])) {
                 $options['macros'] = $host['macros'];
             }
             $result = CHost::massAdd($options);
             if (!$result) {
                 self::exception();
             }
             if (isset($host['profile']) && !empty($host['extendedProfile'])) {
                 $fields = array_keys($host['profile']);
                 $fields = implode(', ', $fields);
                 $values = array_map('zbx_dbstr', $host['profile']);
                 $values = implode(', ', $values);
                 DBexecute('INSERT INTO hosts_profiles (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')');
             }
             if (isset($host['extendedProfile']) && !empty($host['extendedProfile'])) {
                 $fields = array_keys($host['extendedProfile']);
                 $fields = implode(', ', $fields);
                 $values = array_map('zbx_dbstr', $host['extendedProfile']);
                 $values = implode(', ', $values);
                 DBexecute('INSERT INTO hosts_profiles_ext (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')');
             }
         }
         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;
     }
 }
Пример #30
0
/**
 * Format history value.
 * First format the value according to the configuration of the item. Then apply the value mapping to the formatted (!)
 * value.
 *
 * @param mixed     $value
 * @param array     $item
 * @param int       $item['value_type']     type of the value: ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_UINT64, ...
 * @param string    $item['units']          units of item
 * @param int       $item['valuemapid']     id of mapping set of values
 * @param bool      $trim
 *
 * @return string
 */
function formatHistoryValue($value, array $item, $trim = true)
{
    $mapping = false;
    // format value
    if ($item['value_type'] == ITEM_VALUE_TYPE_FLOAT || $item['value_type'] == ITEM_VALUE_TYPE_UINT64) {
        $value = convert_units(array('value' => $value, 'units' => $item['units']));
    } elseif ($item['value_type'] != ITEM_VALUE_TYPE_STR && $item['value_type'] != ITEM_VALUE_TYPE_TEXT && $item['value_type'] != ITEM_VALUE_TYPE_LOG) {
        $value = _('Unknown value type');
    }
    // apply value mapping
    switch ($item['value_type']) {
        case ITEM_VALUE_TYPE_STR:
            $mapping = getMappedValue($value, $item['valuemapid']);
            // break; is not missing here
        // break; is not missing here
        case ITEM_VALUE_TYPE_TEXT:
        case ITEM_VALUE_TYPE_LOG:
            if ($trim && zbx_strlen($value) > 20) {
                $value = zbx_substr($value, 0, 20) . '...';
            }
            if ($mapping !== false) {
                $value = $mapping . ' (' . $value . ')';
            }
            break;
        default:
            $value = applyValueMap($value, $item['valuemapid']);
    }
    return $value;
}