Esempio n. 1
0
 public static function checkAuthentication($sessionid)
 {
     try {
         if ($sessionid !== null) {
             self::$data = API::User()->checkAuthentication($sessionid);
         }
         if ($sessionid === null || empty(self::$data)) {
             self::setDefault();
             self::$data = API::User()->login(array('user' => ZBX_GUEST_USER, 'password' => '', 'userData' => true));
             if (empty(self::$data)) {
                 clear_messages(1);
                 throw new Exception();
             }
             $sessionid = self::$data['sessionid'];
         }
         if (self::$data['gui_access'] == GROUP_GUI_ACCESS_DISABLED) {
             error(_('GUI access disabled.'));
             throw new Exception();
         }
         zbx_setcookie('zbx_sessionid', $sessionid, self::$data['autologin'] ? time() + SEC_PER_DAY * 31 : 0);
         return true;
     } catch (Exception $e) {
         self::setDefault();
         return false;
     }
 }
Esempio n. 2
0
 public static function checkAuthentication($sessionId)
 {
     try {
         if ($sessionId !== null) {
             self::$data = API::User()->checkAuthentication(array($sessionId));
         }
         if ($sessionId === null || empty(self::$data)) {
             self::setDefault();
             self::$data = API::User()->login(array('user' => ZBX_GUEST_USER, 'password' => '', 'userData' => true));
             if (empty(self::$data)) {
                 clear_messages(1);
                 throw new Exception();
             }
             $sessionId = self::$data['sessionid'];
         }
         if (self::$data['gui_access'] == GROUP_GUI_ACCESS_DISABLED) {
             throw new Exception();
         }
         self::setSessionCookie($sessionId);
         return $sessionId;
     } catch (Exception $e) {
         self::setDefault();
         return false;
     }
 }
Esempio n. 3
0
 /**
  * Init class
  * @return true
  */
 public static function init()
 {
     global $zbp;
     // Set Z-BlogPHP Enviroment
     $zbp->option['ZC_RUNINFO_DISPLAY'] = false;
     self::$Route = API_Route::getInstance();
     self::$IO = API_IO::getInstance(isset($_SERVER['ACCEPT']) ? $_SERVER['ACCEPT'] : 'application/json');
     self::$User = API_User::getInstance();
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(API_PATH . '/route'), RecursiveIteratorIterator::CHILD_FIRST);
     foreach ($iterator as $path) {
         $fileName = $path->__toString();
         if ($path->isFile()) {
             include $fileName;
         }
     }
     return true;
 }
Esempio n. 4
0
/**
 * Get action messages.
 *
 * @param array  $alerts
 * @param string $alerts[n]['alertid']
 * @param string $alerts[n]['userid']
 * @param int    $alerts[n]['alerttype']
 * @param array  $alerts[n]['mediatypes']
 * @param string $alerts[n]['clock']
 * @param int    $alerts[n]['esc_step']
 * @param int    $alerts[n]['status']
 * @param int    $alerts[n]['retries']
 * @param string $alerts[n]['subject']
 * @param string $alerts[n]['sendto']
 * @param string $alerts[n]['message']
 * @param string $alerts[n]['error']
 *
 * @return CTableInfo
 */
function getActionMessages(array $alerts)
{
    $dbUsers = API::User()->get(array('output' => array('userid', 'alias', 'name', 'surname'), 'userids' => zbx_objectValues($alerts, 'userid'), 'preservekeys' => true));
    $table = new CTableInfo(_('No actions found.'));
    $table->setHeader(array(_('Time'), _('Type'), _('Status'), _('Retries left'), _('Recipient(s)'), _('Message'), _('Info')));
    foreach ($alerts as $alert) {
        if ($alert['alerttype'] != ALERT_TYPE_MESSAGE) {
            continue;
        }
        $mediaType = array_pop($alert['mediatypes']);
        $time = zbx_date2str(DATE_TIME_FORMAT_SECONDS, $alert['clock']);
        if ($alert['esc_step'] > 0) {
            $time = array(bold(_('Step') . NAME_DELIMITER), $alert['esc_step'], br(), bold(_('Time') . NAME_DELIMITER), br(), $time);
        }
        if ($alert['status'] == ALERT_STATUS_SENT) {
            $status = new CSpan(_('sent'), 'green');
            $retries = new CSpan(SPACE, 'green');
        } elseif ($alert['status'] == ALERT_STATUS_NOT_SENT) {
            $status = new CSpan(_('In progress'), 'orange');
            $retries = new CSpan(ALERT_MAX_RETRIES - $alert['retries'], 'orange');
        } else {
            $status = new CSpan(_('not sent'), 'red');
            $retries = new CSpan(0, 'red');
        }
        $recipient = $alert['userid'] ? array(bold(getUserFullname($dbUsers[$alert['userid']])), BR(), $alert['sendto']) : $alert['sendto'];
        $message = array(bold(_('Subject') . NAME_DELIMITER), br(), $alert['subject'], br(), br(), bold(_('Message') . NAME_DELIMITER));
        array_push($message, BR(), zbx_nl2br($alert['message']));
        if (zbx_empty($alert['error'])) {
            $info = '';
        } else {
            $info = new CDiv(SPACE, 'status_icon iconerror');
            $info->setHint($alert['error'], 'on');
        }
        $table->addRow(array(new CCol($time, 'top'), new CCol(isset($mediaType['description']) ? $mediaType['description'] : '', 'top'), new CCol($status, 'top'), new CCol($retries, 'top'), new CCol($recipient, 'top'), new CCol($message, 'wraptext top'), new CCol($info, 'wraptext top')));
    }
    return $table;
}
Esempio n. 5
0
    } else {
        access_deny(ACCESS_DENY_PAGE);
    }
}
// login via form
if (isset($_REQUEST['enter']) && $_REQUEST['enter'] == _('Sign in')) {
    // try to login
    $autoLogin = getRequest('autologin', 0);
    DBstart();
    $loginSuccess = CWebUser::login(getRequest('name', ''), getRequest('password', ''));
    DBend(true);
    if ($loginSuccess) {
        // save remember login preference
        $user = array('autologin' => $autoLogin);
        if (CWebUser::$data['autologin'] != $autoLogin) {
            API::User()->updateProfile($user);
        }
        $request = getRequest('request');
        $url = zbx_empty($request) ? CWebUser::$data['url'] : $request;
        if (zbx_empty($url) || $url == $page['file']) {
            $url = 'dashboard.php';
        }
        redirect($url);
        exit;
    } else {
        CWebUser::checkAuthentication(null);
    }
} else {
    // login the user from the session, if the session id is empty - login as a guest
    CWebUser::checkAuthentication(CWebUser::getSessionCookie());
}
Esempio n. 6
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     // adding users
     if ($options['selectUsers'] !== null && $options['selectUsers'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'usrgrpid', 'userid', 'users_groups');
         $dbUsers = API::User()->get(['output' => $options['selectUsers'], 'userids' => $relationMap->getRelatedIds(), 'getAccess' => $options['selectUsers'] == API_OUTPUT_EXTEND ? true : null, 'preservekeys' => true]);
         $result = $relationMap->mapMany($result, $dbUsers, 'users');
     }
     // adding usergroup rights
     if ($options['selectRights'] !== null && $options['selectRights'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'groupid', 'rightid', 'rights');
         if (is_array($options['selectRights'])) {
             $pk_field = $this->pk('rights');
             $output_fields = [$pk_field => $this->fieldId($pk_field, 'r')];
             foreach ($options['selectRights'] as $field) {
                 if ($this->hasField($field, 'rights')) {
                     $output_fields[$field] = $this->fieldId($field, 'r');
                 }
             }
             $output_fields = implode(',', $output_fields);
         } else {
             $output_fields = 'r.*';
         }
         $db_rights = DBfetchArray(DBselect('SELECT ' . $output_fields . ' FROM rights r' . ' WHERE ' . dbConditionInt('r.rightid', $relationMap->getRelatedIds()) . (self::$userData['type'] == USER_TYPE_SUPER_ADMIN ? '' : ' AND r.permission>' . PERM_DENY)));
         $db_rights = zbx_toHash($db_rights, 'rightid');
         foreach ($db_rights as &$db_right) {
             unset($db_right['rightid'], $db_right['groupid']);
         }
         unset($db_right);
         $result = $relationMap->mapMany($result, $db_rights, 'rights');
     }
     return $result;
 }
 $addUsrgrpBtn = new CButton('add', _('Add'), 'return PopUp("popup.php?dstfrm=action.edit&srctbl=usrgrp&srcfld1=usrgrpid&srcfld2=name&multiselect=1", 450, 450)', 'link_menu');
 $addUsrgrpBtn->attr('id', 'addusrgrpbtn');
 $usrgrpList->addRow(new CRow(new CCol($addUsrgrpBtn, null, 2), null, 'opmsgUsrgrpListFooter'));
 $userList = new CTable(null, 'formElementTable');
 $userList->setHeader(array(_('User'), _('Action')));
 $userList->attr('style', 'min-width: 310px;');
 $userList->setAttribute('id', 'opmsgUserList');
 $addUserBtn = new CButton('add', _('Add'), 'return PopUp("popup.php?dstfrm=action.edit&srctbl=users&srcfld1=userid&srcfld2=fullname&multiselect=1", 450, 450)', 'link_menu');
 $addUserBtn->attr('id', 'adduserbtn');
 $userList->addRow(new CRow(new CCol($addUserBtn, null, 2), null, 'opmsgUserListFooter'));
 // add participations
 $usrgrpids = isset($this->data['new_operation']['opmessage_grp']) ? zbx_objectValues($this->data['new_operation']['opmessage_grp'], 'usrgrpid') : array();
 $userids = isset($this->data['new_operation']['opmessage_usr']) ? zbx_objectValues($this->data['new_operation']['opmessage_usr'], 'userid') : array();
 $usrgrps = API::UserGroup()->get(array('usrgrpids' => $usrgrpids, 'output' => array('name')));
 order_result($usrgrps, 'name');
 $users = API::User()->get(array('userids' => $userids, 'output' => array('alias', 'name', 'surname')));
 order_result($users, 'alias');
 foreach ($users as &$user) {
     $user['fullname'] = getUserFullname($user);
 }
 unset($user);
 $jsInsert = 'addPopupValues(' . zbx_jsvalue(array('object' => 'usrgrpid', 'values' => $usrgrps)) . ');';
 $jsInsert .= 'addPopupValues(' . zbx_jsvalue(array('object' => 'userid', 'values' => $users)) . ');';
 zbx_add_post_js($jsInsert);
 $newOperationsTable->addRow(array(_('Send to User groups'), new CDiv($usrgrpList, 'objectgroup inlineblock border_dotted ui-corner-all')));
 $newOperationsTable->addRow(array(_('Send to Users'), new CDiv($userList, 'objectgroup inlineblock border_dotted ui-corner-all')));
 $mediaTypeComboBox = new CComboBox('new_operation[opmessage][mediatypeid]', $this->data['new_operation']['opmessage']['mediatypeid']);
 $mediaTypeComboBox->addItem(0, '- ' . _('All') . ' -');
 $dbMediaTypes = DBfetchArray(DBselect('SELECT mt.mediatypeid,mt.description' . ' FROM media_type mt' . whereDbNode('mt.mediatypeid')));
 order_result($dbMediaTypes, 'description');
 foreach ($dbMediaTypes as $dbMediaType) {
Esempio n. 8
0
function getUserFormData($userid, $isProfile = false)
{
    $config = select_config();
    $data = array('is_profile' => $isProfile);
    if (isset($userid)) {
        $users = API::User()->get(array('userids' => $userid, 'output' => API_OUTPUT_EXTEND));
        $user = reset($users);
    }
    if (isset($userid) && (!isset($_REQUEST['form_refresh']) || isset($_REQUEST['register']))) {
        $data['alias'] = $user['alias'];
        $data['name'] = $user['name'];
        $data['surname'] = $user['surname'];
        $data['password1'] = null;
        $data['password2'] = null;
        $data['url'] = $user['url'];
        $data['autologin'] = $user['autologin'];
        $data['autologout'] = $user['autologout'];
        $data['lang'] = $user['lang'];
        $data['theme'] = $user['theme'];
        $data['refresh'] = $user['refresh'];
        $data['rows_per_page'] = $user['rows_per_page'];
        $data['user_type'] = $user['type'];
        $data['messages'] = getMessageSettings();
        $userGroups = API::UserGroup()->get(array('userids' => $userid, 'output' => array('usrgrpid')));
        $userGroup = zbx_objectValues($userGroups, 'usrgrpid');
        $data['user_groups'] = zbx_toHash($userGroup);
        $data['user_medias'] = array();
        $dbMedia = DBselect('SELECT m.mediaid,m.mediatypeid,m.period,m.sendto,m.severity,m.active' . ' FROM media m' . ' WHERE m.userid=' . zbx_dbstr($userid));
        while ($dbMedium = DBfetch($dbMedia)) {
            $data['user_medias'][] = $dbMedium;
        }
        if ($data['autologout'] > 0) {
            $_REQUEST['autologout'] = $data['autologout'];
        }
    } else {
        $data['alias'] = getRequest('alias', '');
        $data['name'] = getRequest('name', '');
        $data['surname'] = getRequest('surname', '');
        $data['password1'] = getRequest('password1', '');
        $data['password2'] = getRequest('password2', '');
        $data['url'] = getRequest('url', '');
        $data['autologin'] = getRequest('autologin', 0);
        $data['autologout'] = getRequest('autologout', 900);
        $data['lang'] = getRequest('lang', 'en_gb');
        $data['theme'] = getRequest('theme', THEME_DEFAULT);
        $data['refresh'] = getRequest('refresh', 30);
        $data['rows_per_page'] = getRequest('rows_per_page', 50);
        $data['user_type'] = getRequest('user_type', USER_TYPE_ZABBIX_USER);
        $data['user_groups'] = getRequest('user_groups', array());
        $data['change_password'] = getRequest('change_password');
        $data['user_medias'] = getRequest('user_medias', array());
        // set messages
        $data['messages'] = getRequest('messages', array());
        if (!isset($data['messages']['enabled'])) {
            $data['messages']['enabled'] = 0;
        }
        if (!isset($data['messages']['sounds.recovery'])) {
            $data['messages']['sounds.recovery'] = 'alarm_ok.wav';
        }
        if (!isset($data['messages']['triggers.recovery'])) {
            $data['messages']['triggers.recovery'] = 0;
        }
        if (!isset($data['messages']['triggers.severities'])) {
            $data['messages']['triggers.severities'] = array();
        }
        $data['messages'] = array_merge(getMessageSettings(), $data['messages']);
    }
    // authentication type
    if ($data['user_groups']) {
        $data['auth_type'] = getGroupAuthenticationType($data['user_groups'], GROUP_GUI_ACCESS_INTERNAL);
    } else {
        $data['auth_type'] = $userid === null ? $config['authentication_type'] : getUserAuthenticationType($userid, GROUP_GUI_ACCESS_INTERNAL);
    }
    // set autologout
    if ($data['autologin'] || !isset($data['autologout'])) {
        $data['autologout'] = 0;
    }
    // set media types
    if (!empty($data['user_medias'])) {
        $mediaTypeDescriptions = array();
        $dbMediaTypes = DBselect('SELECT mt.mediatypeid,mt.description FROM media_type mt WHERE ' . dbConditionInt('mt.mediatypeid', zbx_objectValues($data['user_medias'], 'mediatypeid')));
        while ($dbMediaType = DBfetch($dbMediaTypes)) {
            $mediaTypeDescriptions[$dbMediaType['mediatypeid']] = $dbMediaType['description'];
        }
        foreach ($data['user_medias'] as &$media) {
            $media['description'] = $mediaTypeDescriptions[$media['mediatypeid']];
        }
        unset($media);
        CArrayHelper::sort($data['user_medias'], array('description', 'sendto'));
    }
    // set user rights
    if (!$data['is_profile']) {
        $data['groups'] = API::UserGroup()->get(array('usrgrpids' => $data['user_groups'], 'output' => array('usrgrpid', 'name')));
        order_result($data['groups'], 'name');
        $group_ids = array_values($data['user_groups']);
        if (count($group_ids) == 0) {
            $group_ids = array(-1);
        }
        $db_rights = DBselect('SELECT r.* FROM rights r WHERE ' . dbConditionInt('r.groupid', $group_ids));
        // deny beat all, read-write beat read
        $tmp_permitions = array();
        while ($db_right = DBfetch($db_rights)) {
            if (isset($tmp_permitions[$db_right['id']]) && $tmp_permitions[$db_right['id']] != PERM_DENY) {
                $tmp_permitions[$db_right['id']] = $db_right['permission'] == PERM_DENY ? PERM_DENY : max($tmp_permitions[$db_right['id']], $db_right['permission']);
            } else {
                $tmp_permitions[$db_right['id']] = $db_right['permission'];
            }
        }
        $data['user_rights'] = array();
        foreach ($tmp_permitions as $id => $permition) {
            array_push($data['user_rights'], array('id' => $id, 'permission' => $permition));
        }
    }
    return $data;
}
Esempio n. 9
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     // adding users
     if ($options['selectUsers'] !== null && $options['selectUsers'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'usrgrpid', 'userid', 'users_groups');
         $users = API::User()->get(array('output' => $options['selectUsers'], 'userids' => $relationMap->getRelatedIds(), 'getAccess' => $options['selectUsers'] == API_OUTPUT_EXTEND ? true : null, 'preservekeys' => true));
         $result = $relationMap->mapMany($result, $users, 'users');
     }
     return $result;
 }
Esempio n. 10
0
    $data['autologout'] = getRequest('autologout');
    // render view
    $usersView = new CView('administration.users.edit', $data);
    $usersView->render();
    $usersView->show();
} else {
    $sortField = getRequest('sort', CProfile::get('web.' . $page['file'] . '.sort', 'alias'));
    $sortOrder = getRequest('sortorder', CProfile::get('web.' . $page['file'] . '.sortorder', ZBX_SORT_UP));
    CProfile::update('web.' . $page['file'] . '.sort', $sortField, PROFILE_TYPE_STR);
    CProfile::update('web.' . $page['file'] . '.sortorder', $sortOrder, PROFILE_TYPE_STR);
    $data = array('config' => $config, 'sort' => $sortField, 'sortorder' => $sortOrder);
    // get user groups
    $data['userGroups'] = API::UserGroup()->get(array('output' => API_OUTPUT_EXTEND));
    order_result($data['userGroups'], 'name');
    // get users
    $data['users'] = API::User()->get(array('usrgrpids' => $_REQUEST['filter_usrgrpid'] > 0 ? $_REQUEST['filter_usrgrpid'] : null, 'output' => API_OUTPUT_EXTEND, 'selectUsrgrps' => API_OUTPUT_EXTEND, 'getAccess' => 1, 'limit' => $config['search_limit'] + 1));
    // sorting & paging
    order_result($data['users'], $sortField, $sortOrder);
    $data['paging'] = getPagingLine($data['users'], $sortOrder);
    // set default lastaccess time to 0
    foreach ($data['users'] as $user) {
        $data['usersSessions'][$user['userid']] = array('lastaccess' => 0);
    }
    $dbSessions = DBselect('SELECT s.userid,MAX(s.lastaccess) AS lastaccess,s.status' . ' FROM sessions s' . ' WHERE ' . dbConditionInt('s.userid', zbx_objectValues($data['users'], 'userid')) . ' GROUP BY s.userid,s.status');
    while ($session = DBfetch($dbSessions)) {
        if ($data['usersSessions'][$session['userid']]['lastaccess'] < $session['lastaccess']) {
            $data['usersSessions'][$session['userid']] = $session;
        }
    }
    // render view
    $usersView = new CView('administration.users.list', $data);
Esempio n. 11
0
        insert_js('var popupReference = ' . zbx_jsvalue($userGroups, true) . ';');
    }
    zbx_add_post_js('chkbxRange.pageGoName = "usrgrps";');
    $form->addItem($table);
    $form->show();
} elseif ($srctbl == 'users') {
    $form = new CForm();
    $form->setName('userform');
    $form->setAttribute('id', 'users');
    $table = new CTableInfo(_('No users found.'));
    $table->setHeader(array($multiselect ? new CCheckBox('all_users', null, "javascript: checkAll('" . $form->getName() . "', 'all_users', 'users');") : null, _('Alias'), _('Name'), _('Surname')));
    $options = array('nodeids' => $nodeId, 'output' => array('alias', 'name', 'surname', 'type', 'theme', 'lang'), 'preservekeys' => true);
    if (!is_null($writeonly)) {
        $options['editable'] = true;
    }
    $users = API::User()->get($options);
    order_result($users, 'alias');
    foreach ($users as &$user) {
        $alias = new CSpan($user['alias'], 'link');
        $alias->attr('id', 'spanid' . $user['userid']);
        if (isset($srcfld2) && $srcfld2 == 'fullname') {
            $user[$srcfld2] = getUserFullname($user);
        }
        if ($multiselect) {
            $js_action = 'javascript: addValue(' . zbx_jsvalue($reference) . ', ' . zbx_jsvalue($user['userid']) . ');';
        } else {
            $values = array($dstfld1 => $user[$srcfld1]);
            if (isset($srcfld2)) {
                $values[$dstfld2] = $user[$srcfld2];
            }
            $js_action = 'javascript: addValues(' . zbx_jsvalue($dstfrm) . ', ' . zbx_jsvalue($values) . '); close_window(); return false;';
 /**
  * Get Media types data
  *
  * @param array $options
  * @param array $options['nodeids'] filter by Node IDs
  * @param array $options['mediatypeids'] filter by Mediatype IDs
  * @param boolean $options['type'] filter by Mediatype type [ USER_TYPE_ZABBIX_USER: 1, USER_TYPE_ZABBIX_ADMIN: 2, USER_TYPE_SUPER_ADMIN: 3 ]
  * @param boolean $options['output'] output only Mediatype IDs if not set.
  * @param boolean $options['count'] output only count of objects in result. ( result returned in property 'rowscount' )
  * @param string $options['pattern'] filter by Host name containing only give pattern
  * @param int $options['limit'] output will be limited to given number
  * @param string $options['sortfield'] output will be sorted by given property [ 'mediatypeid', 'alias' ]
  * @param string $options['sortorder'] output will be sorted in given order [ 'ASC', 'DESC' ]
  * @return array
  */
 public function get($options = array())
 {
     $result = array();
     $nodeCheck = false;
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('mediatypeid');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('media_type' => 'mt.mediatypeid'), 'from' => array('media_type' => 'media_type mt'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'mediatypeids' => null, 'mediaids' => null, 'userids' => null, 'editable' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectUsers' => null, 'selectMedias' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // permission check
     if (USER_TYPE_SUPER_ADMIN == $userType) {
     } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) {
     } elseif (!is_null($options['editable']) || self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
         return array();
     }
     // output
     $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // mediatypeids
     if (!is_null($options['mediatypeids'])) {
         zbx_value2array($options['mediatypeids']);
         $sqlParts['where'][] = dbConditionInt('mt.mediatypeid', $options['mediatypeids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('mt.mediatypeid', $nodeids);
         }
     }
     // mediaids
     if (!is_null($options['mediaids'])) {
         zbx_value2array($options['mediaids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['mediaid'] = 'm.mediaid';
         }
         $sqlParts['from']['media'] = 'media m';
         $sqlParts['where'][] = dbConditionInt('m.mediaid', $options['mediaids']);
         $sqlParts['where']['mmt'] = 'm.mediatypeid=mt.mediatypeid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('m.mediaid', $nodeids);
         }
     }
     // userids
     if (!is_null($options['userids'])) {
         zbx_value2array($options['userids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['userid'] = 'm.userid';
         }
         $sqlParts['from']['media'] = 'media m';
         $sqlParts['where'][] = dbConditionInt('m.userid', $options['userids']);
         $sqlParts['where']['mmt'] = 'm.mediatypeid=mt.mediatypeid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('m.userid', $nodeids);
         }
     }
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('mt.mediatypeid', $nodeids);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('media_type mt', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('media_type mt', $options, $sqlParts);
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'mt');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $mediatypeids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($mediatype = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $mediatype;
             } else {
                 $result = $mediatype['rowscount'];
             }
         } else {
             $mediatypeids[$mediatype['mediatypeid']] = $mediatype['mediatypeid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$mediatype['mediatypeid']] = array('mediatypeid' => $mediatype['mediatypeid']);
             } else {
                 if (!isset($result[$mediatype['mediatypeid']])) {
                     $result[$mediatype['mediatypeid']] = array();
                 }
                 // mediaids
                 if (isset($mediatype['mediaid']) && is_null($options['selectMedias'])) {
                     if (!isset($result[$mediatype['mediatypeid']]['medias'])) {
                         $result[$mediatype['mediatypeid']]['medias'] = array();
                     }
                     $result[$mediatype['mediatypeid']]['medias'][] = array('mediaid' => $mediatype['mediaid']);
                     unset($mediatype['mediaid']);
                 }
                 // userids
                 if (isset($mediatype['userid']) && is_null($options['selectUsers'])) {
                     if (!isset($result[$mediatype['mediatypeid']]['users'])) {
                         $result[$mediatype['mediatypeid']]['users'] = array();
                     }
                     $result[$mediatype['mediatypeid']]['users'][] = array('userid' => $mediatype['userid']);
                     unset($mediatype['userid']);
                 }
                 $result[$mediatype['mediatypeid']] += $mediatype;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding users
     if (!is_null($options['selectUsers']) && str_in_array($options['selectUsers'], $subselectsAllowedOutputs)) {
         $users = API::User()->get(array('output' => $options['selectUsers'], 'mediatypeids' => $mediatypeids, 'preservekeys' => true));
         foreach ($users as $user) {
             $umediatypes = $user['mediatypes'];
             unset($user['mediatypes']);
             foreach ($umediatypes as $mediatype) {
                 $result[$mediatype['mediatypeid']]['users'][] = $user;
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 13
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     // adding users
     if ($options['selectUsers'] !== null && $options['selectUsers'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'mediatypeid', 'userid', 'media');
         $users = API::User()->get(['output' => $options['selectUsers'], 'userids' => $relationMap->getRelatedIds(), 'preservekeys' => true]);
         $result = $relationMap->mapMany($result, $users, 'users');
     }
     return $result;
 }
Esempio n. 14
0
    }
}
if (!$data['alias'] || $data['users']) {
    $from = zbxDateToTime($data['stime']);
    $till = $from + $effectivePeriod;
    // fetch alerts for different objects and sources and combine them in a single stream
    foreach (eventSourceObjects() as $eventSource) {
        $data['alerts'] = array_merge($data['alerts'], API::Alert()->get(array('output' => API_OUTPUT_EXTEND, 'selectMediatypes' => API_OUTPUT_EXTEND, 'userids' => $userId, 'time_from' => $from, 'time_till' => $till, 'eventsource' => $eventSource['source'], 'eventobject' => $eventSource['object'], 'limit' => $config['search_limit'] + 1)));
    }
    CArrayHelper::sort($data['alerts'], array(array('field' => 'alertid', 'order' => ZBX_SORT_DOWN)));
    $data['alerts'] = array_slice($data['alerts'], 0, $config['search_limit'] + 1);
    // paging
    $data['paging'] = getPagingLine($data['alerts']);
    // get users
    if (!$data['alias']) {
        $data['users'] = API::User()->get(array('output' => array('userid', 'alias', 'name', 'surname'), 'userids' => zbx_objectValues($data['alerts'], 'userid'), 'preservekeys' => true));
    }
}
// get first alert clock
$firstAlert = null;
if ($userId) {
    $firstAlert = DBfetch(DBselect('SELECT MIN(a.clock) AS clock' . ' FROM alerts a' . ' WHERE a.userid=' . zbx_dbstr($userId)));
} elseif ($data['alias'] === '') {
    $firstAlert = DBfetch(DBselect('SELECT MIN(a.clock) AS clock FROM alerts a'));
}
$minStartTime = $firstAlert ? $firstAlert['clock'] : null;
// get actions names
if ($data['alerts']) {
    $data['actions'] = API::Action()->get(array('output' => array('actionid', 'name'), 'actionids' => array_unique(zbx_objectValues($data['alerts'], 'actionid')), 'preservekeys' => true));
}
// timeline
}
$_REQUEST['alias'] = get_request('alias', CProfile::get('web.auditacts.filter.alias', ''));
if (isset($_REQUEST['filter_set']) || isset($_REQUEST['filter_rst'])) {
    CProfile::update('web.auditacts.filter.alias', $_REQUEST['alias'], PROFILE_TYPE_STR);
}
/*
 * Display
 */
$effectivePeriod = navigation_bar_calc('web.auditacts.timeline', 0, true);
$data = array('stime' => get_request('stime'), 'alias' => get_request('alias'), 'alerts' => array());
$from = zbxDateToTime($data['stime']);
$till = $from + $effectivePeriod;
// get alerts
$options = array('time_from' => $from, 'time_till' => $till, 'output' => API_OUTPUT_EXTEND, 'selectMediatypes' => API_OUTPUT_EXTEND, 'sortfield' => 'alertid', 'sortorder' => ZBX_SORT_DOWN, 'limit' => $config['search_limit'] + 1);
if (!empty($data['alias'])) {
    $users = API::User()->get(array('filter' => array('alias' => $data['alias'])));
    $options['userids'] = zbx_objectValues($users, 'userid');
}
$data['alerts'] = API::Alert()->get($options);
// get paging
$data['paging'] = getPagingLine($data['alerts']);
// get timeline
unset($options['userids'], $options['time_from'], $options['time_till'], $options['selectMediatypes']);
$options['limit'] = 1;
$options['sortorder'] = ZBX_SORT_UP;
$firstAlert = API::Alert()->get($options);
$firstAlert = reset($firstAlert);
$data['timeline'] = array('period' => $effectivePeriod, 'starttime' => date('YmdHis', !empty($firstAlert) ? $firstAlert['clock'] : time() - SEC_PER_HOUR), 'usertime' => isset($data['stime']) ? date('YmdHis', zbxDateToTime($data['stime']) + $effectivePeriod) : null);
// render view
$auditView = new CView('administration.auditacts.list', $data);
$auditView->render();
Esempio n. 16
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $sortfield = 'clock';
     $sortorder = ZBX_SORT_DOWN;
     switch ($this->screenitem['sort_triggers']) {
         case SCREEN_SORT_TRIGGERS_TIME_ASC:
             $sortfield = 'clock';
             $sortorder = ZBX_SORT_UP;
             break;
         case SCREEN_SORT_TRIGGERS_TIME_DESC:
             $sortfield = 'clock';
             $sortorder = ZBX_SORT_DOWN;
             break;
         case SCREEN_SORT_TRIGGERS_TYPE_ASC:
             $sortfield = 'description';
             $sortorder = ZBX_SORT_UP;
             break;
         case SCREEN_SORT_TRIGGERS_TYPE_DESC:
             $sortfield = 'description';
             $sortorder = ZBX_SORT_DOWN;
             break;
         case SCREEN_SORT_TRIGGERS_STATUS_ASC:
             $sortfield = 'status';
             $sortorder = ZBX_SORT_UP;
             break;
         case SCREEN_SORT_TRIGGERS_STATUS_DESC:
             $sortfield = 'status';
             $sortorder = ZBX_SORT_DOWN;
             break;
         case SCREEN_SORT_TRIGGERS_RECIPIENT_ASC:
             $sortfield = 'sendto';
             $sortorder = ZBX_SORT_UP;
             break;
         case SCREEN_SORT_TRIGGERS_RECIPIENT_DESC:
             $sortfield = 'sendto';
             $sortorder = ZBX_SORT_DOWN;
             break;
     }
     $sql = 'SELECT a.alertid,a.clock,a.sendto,a.subject,a.message,a.status,a.retries,a.error,' . 'a.userid,a.actionid,a.mediatypeid,mt.description' . ' FROM events e,alerts a' . ' LEFT JOIN media_type mt ON mt.mediatypeid=a.mediatypeid' . ' WHERE e.eventid=a.eventid' . ' AND alerttype=' . ALERT_TYPE_MESSAGE;
     if (CWebUser::getType() != USER_TYPE_SUPER_ADMIN) {
         $userid = CWebUser::$data['userid'];
         $userGroups = getUserGroupsByUserId($userid);
         $sql .= ' AND EXISTS (' . 'SELECT NULL' . ' FROM functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY f.triggerid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ')';
     }
     $sql .= ' ORDER BY ' . $sortfield . ' ' . $sortorder;
     $alerts = DBfetchArray(DBselect($sql, $this->screenitem['elements']));
     order_result($alerts, $sortfield, $sortorder);
     $userids = [];
     foreach ($alerts as $alert) {
         if ($alert['userid'] != 0) {
             $userids[$alert['userid']] = true;
         }
     }
     if ($userids) {
         $dbUsers = API::User()->get(['output' => ['userid', 'alias', 'name', 'surname'], 'userids' => array_keys($userids), 'preservekeys' => true]);
     }
     // indicator of sort field
     $sort_div = (new CSpan())->addClass($sortorder === ZBX_SORT_DOWN ? ZBX_STYLE_ARROW_DOWN : ZBX_STYLE_ARROW_UP);
     // create alert table
     $table = (new CTableInfo())->setHeader([$sortfield === 'clock' ? ['Time', $sort_div] : _('Time'), _('Action'), $sortfield === 'description' ? [_('Type'), $sort_div] : _('Type'), $sortfield === 'sendto' ? [_('Recipient(s)'), $sort_div] : _('Recipient(s)'), _('Message'), $sortfield === 'status' ? [_('Status'), $sort_div] : _('Status'), _('Info')]);
     $actions = API::Action()->get(['output' => ['actionid', 'name'], 'actionids' => array_unique(zbx_objectValues($alerts, 'actionid')), 'preservekeys' => true]);
     foreach ($alerts as $alert) {
         if ($alert['status'] == ALERT_STATUS_SENT) {
             $status = (new CSpan(_('Sent')))->addClass(ZBX_STYLE_GREEN);
         } elseif ($alert['status'] == ALERT_STATUS_NOT_SENT) {
             $status = (new CSpan([_('In progress') . ':', BR(), _n('%1$s retry left', '%1$s retries left', ALERT_MAX_RETRIES - $alert['retries'])]))->addClass(ZBX_STYLE_YELLOW);
         } else {
             $status = (new CSpan(_('Not sent')))->addClass(ZBX_STYLE_RED);
         }
         $recipient = $alert['userid'] != 0 ? [bold(getUserFullname($dbUsers[$alert['userid']])), BR(), $alert['sendto']] : $alert['sendto'];
         $table->addRow([zbx_date2str(DATE_TIME_FORMAT_SECONDS, $alert['clock']), $actions[$alert['actionid']]['name'], $alert['mediatypeid'] == 0 ? '' : $alert['description'], $recipient, [bold($alert['subject']), BR(), BR(), zbx_nl2br($alert['message'])], $status, $alert['error'] === '' ? '' : makeErrorIcon($alert['error'])]);
     }
     $footer = (new CList())->addItem(_s('Updated: %s', zbx_date2str(TIME_FORMAT_SECONDS)))->addClass(ZBX_STYLE_DASHBRD_WIDGET_FOOT);
     return $this->getOutput((new CUiWidget(uniqid(), [$table, $footer]))->setHeader(_('Action log')));
 }
Esempio n. 17
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     $alertIds = array_keys($result);
     // adding hosts
     if ($options['selectHosts'] !== null && $options['selectHosts'] !== API_OUTPUT_COUNT) {
         // trigger events
         if ($options['eventobject'] == EVENT_OBJECT_TRIGGER) {
             $query = DBselect('SELECT a.alertid,i.hostid' . ' FROM alerts a,events e,functions f,items i' . ' WHERE ' . dbConditionInt('a.alertid', $alertIds) . ' AND a.eventid=e.eventid' . ' AND e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND e.object=' . zbx_dbstr($options['eventobject']) . ' AND e.source=' . zbx_dbstr($options['eventsource']));
         } elseif ($options['eventobject'] == EVENT_OBJECT_ITEM || $options['eventobject'] == EVENT_OBJECT_LLDRULE) {
             $query = DBselect('SELECT a.alertid,i.hostid' . ' FROM alerts a,events e,items i' . ' WHERE ' . dbConditionInt('a.alertid', $alertIds) . ' AND a.eventid=e.eventid' . ' AND e.objectid=i.itemid' . ' AND e.object=' . zbx_dbstr($options['eventobject']) . ' AND e.source=' . zbx_dbstr($options['eventsource']));
         }
         $relationMap = new CRelationMap();
         while ($relation = DBfetch($query)) {
             $relationMap->addRelation($relation['alertid'], $relation['hostid']);
         }
         $hosts = API::Host()->get(['output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'preservekeys' => true]);
         $result = $relationMap->mapMany($result, $hosts, 'hosts');
     }
     // adding users
     if ($options['selectUsers'] !== null && $options['selectUsers'] !== API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'alertid', 'userid');
         $users = API::User()->get(['output' => $options['selectUsers'], 'userids' => $relationMap->getRelatedIds(), 'preservekeys' => true]);
         $result = $relationMap->mapMany($result, $users, 'users');
     }
     // adding media types
     if ($options['selectMediatypes'] !== null && $options['selectMediatypes'] !== API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'alertid', 'mediatypeid');
         $mediatypes = API::getApiService()->select('media_type', ['output' => $options['selectMediatypes'], 'filter' => ['mediatypeid' => $relationMap->getRelatedIds()], 'preservekeys' => true]);
         $result = $relationMap->mapMany($result, $mediatypes, 'mediatypes');
     }
     return $result;
 }
Esempio n. 18
0
         $userids[$user['userid']] = $user['userid'];
     }
     foreach (getRequest('userGroups', []) as $user_group) {
         $user_groupids[$user_group['usrgrpid']] = $user_group['usrgrpid'];
     }
 } else {
     // Map owner.
     $userids[$sysmap['userid']] = $sysmap['userid'];
     foreach ($sysmap['users'] as $user) {
         $userids[$user['userid']] = $user['userid'];
     }
     foreach ($sysmap['userGroups'] as $user_group) {
         $user_groupids[$user_group['usrgrpid']] = $user_group['usrgrpid'];
     }
 }
 $data['users'] = API::User()->get(['output' => ['userid', 'alias', 'name', 'surname'], 'userids' => $userids, 'preservekeys' => true]);
 $data['user_groups'] = API::UserGroup()->get(['output' => ['usrgrpid', 'name'], 'usrgrpids' => $user_groupids, 'preservekeys' => true]);
 if (!hasRequest('sysmapid') || hasRequest('form_refresh')) {
     $data['sysmap'] = ['sysmapid' => getRequest('sysmapid'), 'name' => getRequest('name', ''), 'width' => getRequest('width', 800), 'height' => getRequest('height', 600), 'backgroundid' => getRequest('backgroundid', 0), 'iconmapid' => getRequest('iconmapid', 0), 'label_format' => getRequest('label_format', 0), 'label_type_host' => getRequest('label_type_host', 2), 'label_type_hostgroup' => getRequest('label_type_hostgroup', 2), 'label_type_trigger' => getRequest('label_type_trigger', 2), 'label_type_map' => getRequest('label_type_map', 2), 'label_type_image' => getRequest('label_type_image', 2), 'label_string_host' => getRequest('label_string_host', ''), 'label_string_hostgroup' => getRequest('label_string_hostgroup', ''), 'label_string_trigger' => getRequest('label_string_trigger', ''), 'label_string_map' => getRequest('label_string_map', ''), 'label_string_image' => getRequest('label_string_image', ''), 'label_type' => getRequest('label_type', 0), 'label_location' => getRequest('label_location', 0), 'highlight' => getRequest('highlight', 0), 'markelements' => getRequest('markelements', 0), 'expandproblem' => getRequest('expandproblem', 0), 'show_unack' => getRequest('show_unack', 0), 'severity_min' => getRequest('severity_min', TRIGGER_SEVERITY_NOT_CLASSIFIED), 'urls' => getRequest('urls', []), 'userid' => getRequest('userid', hasRequest('form_refresh') ? '' : $current_userid), 'private' => getRequest('private', PRIVATE_SHARING), 'users' => getRequest('users', []), 'userGroups' => getRequest('userGroups', [])];
 } else {
     $data['sysmap'] = $sysmap;
 }
 $data['current_user_userid'] = $current_userid;
 $data['form_refresh'] = getRequest('form_refresh');
 // config
 $data['config'] = select_config();
 // advanced labels
 $data['labelTypes'] = sysmapElementLabel();
 $data['labelTypesLimited'] = $data['labelTypes'];
 unset($data['labelTypesLimited'][MAP_LABEL_TYPE_IP]);
 $data['labelTypesImage'] = $data['labelTypesLimited'];
Esempio n. 19
0
$_REQUEST['alias'] = isset($_REQUEST['filter_rst']) ? '' : get_request('alias', CProfile::get('web.auditacts.filter.alias', ''));
if (isset($_REQUEST['filter_set']) || isset($_REQUEST['filter_rst'])) {
    CProfile::update('web.auditacts.filter.alias', $_REQUEST['alias'], PROFILE_TYPE_STR);
}
/*
 * Display
 */
$effectivePeriod = navigation_bar_calc('web.auditacts.timeline', 0, true);
$data = array('stime' => get_request('stime'), 'alias' => get_request('alias'), 'alerts' => array());
$from = zbxDateToTime($data['stime']);
$till = $from + $effectivePeriod;
$user = null;
$queryData = true;
$firstAlert = null;
if ($data['alias']) {
    $user = API::User()->get(array('output' => array('userid'), 'filter' => array('alias' => $data['alias'])));
    if ($user) {
        $user = reset($user);
    } else {
        $queryData = false;
    }
}
// fetch alerts for different objects and sources and combine them in a single stream
if ($queryData) {
    foreach (eventSourceObjects() as $eventSource) {
        $data['alerts'] = array_merge($data['alerts'], API::Alert()->get(array('output' => API_OUTPUT_EXTEND, 'selectMediatypes' => API_OUTPUT_EXTEND, 'userids' => $data['alias'] ? $user['userid'] : null, 'time_from' => $from, 'time_till' => $till, 'eventsource' => $eventSource['source'], 'eventobject' => $eventSource['object'], 'limit' => $config['search_limit'] + 1)));
    }
    CArrayHelper::sort($data['alerts'], array(array('field' => 'alertid', 'order' => ZBX_SORT_DOWN)));
    $data['alerts'] = array_slice($data['alerts'], 0, $config['search_limit'] + 1);
    // get first alert
    if ($user) {
Esempio n. 20
0
 /**
  * Get Alerts data.
  *
  * @param array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['alertids']
  * @param array $options['applicationids']
  * @param array $options['status']
  * @param array $options['editable']
  * @param array $options['extendoutput']
  * @param array $options['count']
  * @param array $options['pattern']
  * @param array $options['limit']
  * @param array $options['order']
  *
  * @return array|int item data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('alertid', 'clock', 'eventid', 'status');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('alerts' => 'a.alertid'), 'from' => array('alerts' => 'alerts a'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'alertids' => null, 'triggerids' => null, 'eventids' => null, 'actionids' => null, 'mediatypeids' => null, 'userids' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'time_from' => null, 'time_till' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectMediatypes' => null, 'selectUsers' => null, 'selectHosts' => null, 'countOutput' => null, 'preservekeys' => null, 'editable' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['alerts']);
         $dbTable = DB::getSchema('alerts');
         $sqlParts['select']['alertid'] = 'a.alertid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'a.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM events e,functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE a.eventid=e.eventid' . ' AND e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' AND e.object=' . EVENT_OBJECT_TRIGGER . ' GROUP BY e.eventid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sqlParts['where']['e'] = 'e.object=' . EVENT_OBJECT_TRIGGER;
         $sqlParts['where']['ef'] = 'e.objectid=f.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         $sqlParts['where']['hg'] = dbConditionInt('hg.groupid', $options['groupids']);
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['hostid'] = 'i.hostid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where']['i'] = dbConditionInt('i.hostid', $options['hostids']);
         $sqlParts['where']['e'] = 'e.object=' . EVENT_OBJECT_TRIGGER;
         $sqlParts['where']['ef'] = 'e.objectid=f.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // alertids
     if (!is_null($options['alertids'])) {
         zbx_value2array($options['alertids']);
         $sqlParts['where'][] = dbConditionInt('a.alertid', $options['alertids']);
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['actionid'] = 'a.actionid';
         }
         $sqlParts['where']['ae'] = 'a.eventid=e.eventid';
         $sqlParts['where']['e'] = 'e.object=' . EVENT_OBJECT_TRIGGER;
         $sqlParts['where'][] = dbConditionInt('e.objectid', $options['triggerids']);
     }
     // eventids
     if (!is_null($options['eventids'])) {
         zbx_value2array($options['eventids']);
         $sqlParts['where'][] = dbConditionInt('a.eventid', $options['eventids']);
     }
     // actionids
     if (!is_null($options['actionids'])) {
         zbx_value2array($options['actionids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['actionid'] = 'a.actionid';
         }
         $sqlParts['where'][] = dbConditionInt('a.actionid', $options['actionids']);
     }
     // userids
     if (!is_null($options['userids'])) {
         zbx_value2array($options['userids']);
         $field = 'a.userid';
         if (!is_null($options['time_from']) || !is_null($options['time_till'])) {
             $field = '(a.userid+0)';
         }
         $sqlParts['where'][] = dbConditionInt($field, $options['userids']);
     }
     // mediatypeids
     if (!is_null($options['mediatypeids'])) {
         zbx_value2array($options['mediatypeids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['mediatypeid'] = 'a.mediatypeid';
         }
         $sqlParts['where'][] = dbConditionInt('a.mediatypeid', $options['mediatypeids']);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('alerts a', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('alerts a', $options, $sqlParts);
     }
     // time_from
     if (!is_null($options['time_from'])) {
         $sqlParts['where'][] = 'a.clock>' . zbx_dbstr($options['time_from']);
     }
     // time_till
     if (!is_null($options['time_till'])) {
         $sqlParts['where'][] = 'a.clock<' . zbx_dbstr($options['time_till']);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['alerts'] = 'a.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT a.alertid) AS rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'a');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $alertids = array();
     $userids = array();
     $hostids = array();
     $mediatypeids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('a.alertid', $nodeids) . $sqlWhere . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     while ($alert = DBfetch($dbRes)) {
         if ($options['countOutput']) {
             $result = $alert['rowscount'];
         } else {
             $alertids[$alert['alertid']] = $alert['alertid'];
             if (isset($alert['userid'])) {
                 $userids[$alert['userid']] = $alert['userid'];
             }
             if (isset($alert['hostid'])) {
                 $hostids[$alert['hostid']] = $alert['hostid'];
             }
             if (isset($alert['mediatypeid'])) {
                 $mediatypeids[$alert['mediatypeid']] = $alert['mediatypeid'];
             }
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$alert['alertid']] = array('alertid' => $alert['alertid']);
             } else {
                 if (!isset($result[$alert['alertid']])) {
                     $result[$alert['alertid']] = array();
                 }
                 if (!is_null($options['selectMediatypes']) && !isset($result[$alert['alertid']]['mediatypes'])) {
                     $result[$alert['alertid']]['mediatypes'] = array();
                 }
                 if (!is_null($options['selectUsers']) && !isset($result[$alert['alertid']]['users'])) {
                     $result[$alert['alertid']]['users'] = array();
                 }
                 // hostids
                 if (isset($alert['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$alert['alertid']]['hosts'])) {
                         $result[$alert['alertid']]['hosts'] = array();
                     }
                     $result[$alert['alertid']]['hosts'][] = array('hostid' => $alert['hostid']);
                 }
                 // userids
                 if (isset($alert['userid']) && is_null($options['selectUsers'])) {
                     if (!isset($result[$alert['alertid']]['users'])) {
                         $result[$alert['alertid']]['users'] = array();
                     }
                     $result[$alert['alertid']]['users'][] = array('userid' => $alert['userid']);
                 }
                 // mediatypeids
                 if (isset($alert['mediatypeid']) && is_null($options['selectMediatypes'])) {
                     if (!isset($result[$alert['alertid']]['mediatypes'])) {
                         $result[$alert['alertid']]['mediatypes'] = array();
                     }
                     $result[$alert['alertid']]['mediatypes'][] = array('mediatypeid' => $alert['mediatypeid']);
                 }
                 $result[$alert['alertid']] += $alert;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     $hosts = array();
     $users = array();
     $mediatypes = array();
     // adding hosts
     if (!is_null($options['selectHosts']) && str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
         $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostids' => $hostids, 'preservekeys' => true));
     }
     // adding users
     if (!is_null($options['selectUsers']) && str_in_array($options['selectUsers'], $subselectsAllowedOutputs)) {
         $users = API::User()->get(array('output' => $options['selectUsers'], 'userids' => $userids, 'preservekeys' => true));
     }
     // adding mediatypes
     if (!is_null($options['selectMediatypes']) && str_in_array($options['selectMediatypes'], $subselectsAllowedOutputs)) {
         $res = DBselect('SELECT mt.* FROM media_type mt WHERE ' . dbConditionInt('mt.mediatypeid', $mediatypeids));
         while ($media = DBfetch($res)) {
             $mediatypes[$media['mediatypeid']] = $media;
         }
     }
     foreach ($result as $alertid => $alert) {
         if (isset($alert['hostid']) && isset($hosts[$alert['hostid']])) {
             $result[$alertid]['hosts'][] = $hosts[$alert['hostid']];
         }
         if (isset($mediatypes[$alert['mediatypeid']])) {
             $result[$alertid]['mediatypes'][] = $mediatypes[$alert['mediatypeid']];
         }
         if (isset($users[$alert['userid']])) {
             $result[$alertid]['users'][] = $users[$alert['userid']];
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 21
0
if ($config['authentication_type'] == ZBX_AUTH_HTTP) {
    if (!empty($_SERVER['PHP_AUTH_USER'])) {
        $_REQUEST['enter'] = _('Sign in');
        $_REQUEST['name'] = $_SERVER['PHP_AUTH_USER'];
    } else {
        access_deny();
    }
}
// login via form
if (isset($_REQUEST['enter']) && $_REQUEST['enter'] == _('Sign in')) {
    // try to login
    if (CWebUser::login(get_request('name', ''), get_request('password', ''))) {
        // save remember login preference
        $user = array('autologin' => get_request('autologin', 0));
        if (CWebUser::$data['autologin'] != $user['autologin']) {
            $result = API::User()->updateProfile($user);
        }
        add_audit_ext(AUDIT_ACTION_LOGIN, AUDIT_RESOURCE_USER, CWebUser::$data['userid'], '', null, null, null);
        $request = get_request('request');
        $url = zbx_empty($request) ? CWebUser::$data['url'] : $request;
        if (zbx_empty($url) || $url == $page['file']) {
            $url = 'dashboard.php';
        }
        redirect($url);
        exit;
    } else {
        CWebUser::checkAuthentication(null);
    }
} else {
    // login the user from the session, if the session id is empty - login as a guest
    CWebUser::checkAuthentication(get_cookie('zbx_sessionid'));
Esempio n. 22
0
function makeEventsActions($eventids)
{
    if (!$eventids) {
        return [];
    }
    $result = DBselect('SELECT a.eventid,a.mediatypeid,a.userid,a.clock,a.message,a.status,a.alerttype,a.error' . ' FROM alerts a' . ' WHERE ' . dbConditionInt('a.eventid', $eventids) . ' AND a.alerttype IN (' . ALERT_TYPE_MESSAGE . ',' . ALERT_TYPE_COMMAND . ')' . ' ORDER BY a.alertid DESC');
    $events = [];
    $userids = [];
    $users = [];
    $mediatypeids = [];
    $mediatypes = [];
    while ($row = DBfetch($result)) {
        if (!array_key_exists($row['eventid'], $events)) {
            $events[$row['eventid']] = [ALERT_STATUS_NOT_SENT => [], ALERT_STATUS_SENT => [], ALERT_STATUS_FAILED => []];
        }
        $event = ['clock' => $row['clock'], 'alerttype' => $row['alerttype'], 'error' => $row['error']];
        switch ($event['alerttype']) {
            case ALERT_TYPE_COMMAND:
                $event['message'] = $row['message'];
                break;
            case ALERT_TYPE_MESSAGE:
                $event['mediatypeid'] = $row['mediatypeid'];
                $event['userid'] = $row['userid'];
                if ($event['mediatypeid'] != 0) {
                    $mediatypeids[$row['mediatypeid']] = true;
                }
                if ($event['userid'] != 0) {
                    $userids[$row['userid']] = true;
                }
                break;
        }
        $events[$row['eventid']][$row['status']][] = $event;
    }
    if ($mediatypeids) {
        $mediatypes = API::Mediatype()->get(['output' => ['description'], 'mediatypeids' => array_keys($mediatypeids), 'preservekeys' => true]);
    }
    if ($userids) {
        $users = API::User()->get(['output' => ['alias', 'name', 'surname'], 'userids' => array_keys($userids), 'preservekeys' => true]);
    }
    foreach ($events as $eventid => &$event) {
        $event = (new CList([$event[ALERT_STATUS_SENT] ? (new CSpan(count($event[ALERT_STATUS_SENT])))->addClass(ZBX_STYLE_LINK_ACTION)->addClass(ZBX_STYLE_GREEN)->setHint(makeActionHints($event[ALERT_STATUS_SENT], $mediatypes, $users, ALERT_STATUS_SENT)) : '', $event[ALERT_STATUS_NOT_SENT] ? (new CSpan(count($event[ALERT_STATUS_NOT_SENT])))->addClass(ZBX_STYLE_LINK_ACTION)->addClass(ZBX_STYLE_YELLOW)->setHint(makeActionHints($event[ALERT_STATUS_NOT_SENT], $mediatypes, $users, ALERT_STATUS_NOT_SENT)) : '', $event[ALERT_STATUS_FAILED] ? (new CSpan(count($event[ALERT_STATUS_FAILED])))->addClass(ZBX_STYLE_LINK_ACTION)->addClass(ZBX_STYLE_RED)->setHint(makeActionHints($event[ALERT_STATUS_FAILED], $mediatypes, $users, ALERT_STATUS_FAILED)) : '']))->addClass(ZBX_STYLE_LIST_HOR_MIN_WIDTH);
    }
    unset($event);
    return $events;
}
Esempio n. 23
0
/**
 * Generates array with HTML items representing operation with description
 *
 * @param int $type short or long description, use const. SHORT_DESCRIPTION and LONG_DESCRIPTION
 * @param array $data
 * @param int $data['operationtype'] type of operation: OPERATION_TYPE_MESSAGE, OPERATION_TYPE_COMMAND, ...
 * @param int $data['opmessage']['mediatypeid'] type id of message media
 * @param bool $data['opmessage']['default_msg'] should default message be used
 * @param bool $data['opmessage']['operationid'] if true $data['operationid'] will be used to retrieve default messages from DB
 * @param string $data['opmessage']['subject'] subject of message
 * @param string $data['opmessage']['message'] message it self
 * @param array $data['opmessage_usr'] list of user ids if OPERATION_TYPE_MESSAGE
 * @param array $data['opmessage_grp'] list of group ids if OPERATION_TYPE_MESSAGE
 * @param array $data['opcommand_grp'] list of group ids if OPERATION_TYPE_COMMAND
 * @param array $data['opcommand_hst'] list of host ids if OPERATION_TYPE_COMMAND
 * @param array $data['opgroup'] list of group ids if OPERATION_TYPE_GROUP_ADD or OPERATION_TYPE_GROUP_REMOVE
 * @param array $data['optemplate'] list of template ids if OPERATION_TYPE_TEMPLATE_ADD or OPERATION_TYPE_TEMPLATE_REMOVE
 * @param int $data['operationid'] id of operation
 * @param int $data['opcommand']['type'] type of command: ZBX_SCRIPT_TYPE_IPMI, ZBX_SCRIPT_TYPE_SSH, ...
 * @param string $data['opcommand']['command'] actual command
 * @param int $data['opcommand']['scriptid'] script id used if $data['opcommand']['type'] is ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT
 *
 * @return array
 */
function get_operation_descr($type, $data)
{
    $result = array();
    if ($type == SHORT_DESCRIPTION) {
        switch ($data['operationtype']) {
            case OPERATION_TYPE_MESSAGE:
                $mediaTypes = API::Mediatype()->get(array('mediatypeids' => $data['opmessage']['mediatypeid'], 'output' => array('description')));
                if (empty($mediaTypes)) {
                    $mediatype = _('all media');
                } else {
                    $mediatype = reset($mediaTypes);
                    $mediatype = $mediatype['description'];
                }
                if (!empty($data['opmessage_usr'])) {
                    $users = API::User()->get(array('userids' => zbx_objectValues($data['opmessage_usr'], 'userid'), 'output' => array('userid', 'alias', 'name', 'surname')));
                    order_result($users, 'alias');
                    foreach ($users as $user) {
                        $fullnames[] = getUserFullname($user);
                    }
                    $result[] = bold(_('Send message to users') . NAME_DELIMITER);
                    $result[] = array(implode(', ', $fullnames), SPACE, _('via'), SPACE, $mediatype);
                    $result[] = BR();
                }
                if (!empty($data['opmessage_grp'])) {
                    $usrgrps = API::UserGroup()->get(array('usrgrpids' => zbx_objectValues($data['opmessage_grp'], 'usrgrpid'), 'output' => API_OUTPUT_EXTEND));
                    order_result($usrgrps, 'name');
                    $result[] = bold(_('Send message to user groups') . NAME_DELIMITER);
                    $result[] = array(implode(', ', zbx_objectValues($usrgrps, 'name')), SPACE, _('via'), SPACE, $mediatype);
                    $result[] = BR();
                }
                break;
            case OPERATION_TYPE_COMMAND:
                if (!isset($data['opcommand_grp'])) {
                    $data['opcommand_grp'] = array();
                }
                if (!isset($data['opcommand_hst'])) {
                    $data['opcommand_hst'] = array();
                }
                $hosts = API::Host()->get(array('hostids' => zbx_objectValues($data['opcommand_hst'], 'hostid'), 'output' => array('hostid', 'name')));
                foreach ($data['opcommand_hst'] as $cmd) {
                    if ($cmd['hostid'] != 0) {
                        continue;
                    }
                    $result[] = array(bold(_('Run remote commands on current host')), BR());
                    break;
                }
                if (!empty($hosts)) {
                    order_result($hosts, 'name');
                    $result[] = bold(_('Run remote commands on hosts') . NAME_DELIMITER);
                    $result[] = array(implode(', ', zbx_objectValues($hosts, 'name')), BR());
                }
                $groups = API::HostGroup()->get(array('groupids' => zbx_objectValues($data['opcommand_grp'], 'groupid'), 'output' => array('groupid', 'name')));
                if (!empty($groups)) {
                    order_result($groups, 'name');
                    $result[] = bold(_('Run remote commands on host groups') . NAME_DELIMITER);
                    $result[] = array(implode(', ', zbx_objectValues($groups, 'name')), BR());
                }
                break;
            case OPERATION_TYPE_HOST_ADD:
                $result[] = array(bold(_('Add host')), BR());
                break;
            case OPERATION_TYPE_HOST_REMOVE:
                $result[] = array(bold(_('Remove host')), BR());
                break;
            case OPERATION_TYPE_HOST_ENABLE:
                $result[] = array(bold(_('Enable host')), BR());
                break;
            case OPERATION_TYPE_HOST_DISABLE:
                $result[] = array(bold(_('Disable host')), BR());
                break;
            case OPERATION_TYPE_GROUP_ADD:
            case OPERATION_TYPE_GROUP_REMOVE:
                if (!isset($data['opgroup'])) {
                    $data['opgroup'] = array();
                }
                $groups = API::HostGroup()->get(array('groupids' => zbx_objectValues($data['opgroup'], 'groupid'), 'output' => array('groupid', 'name')));
                if (!empty($groups)) {
                    order_result($groups, 'name');
                    if (OPERATION_TYPE_GROUP_ADD == $data['operationtype']) {
                        $result[] = bold(_('Add to host groups') . NAME_DELIMITER);
                    } else {
                        $result[] = bold(_('Remove from host groups') . NAME_DELIMITER);
                    }
                    $result[] = array(implode(', ', zbx_objectValues($groups, 'name')), BR());
                }
                break;
            case OPERATION_TYPE_TEMPLATE_ADD:
            case OPERATION_TYPE_TEMPLATE_REMOVE:
                if (!isset($data['optemplate'])) {
                    $data['optemplate'] = array();
                }
                $templates = API::Template()->get(array('templateids' => zbx_objectValues($data['optemplate'], 'templateid'), 'output' => array('hostid', 'name')));
                if (!empty($templates)) {
                    order_result($templates, 'name');
                    if (OPERATION_TYPE_TEMPLATE_ADD == $data['operationtype']) {
                        $result[] = bold(_('Link to templates') . NAME_DELIMITER);
                    } else {
                        $result[] = bold(_('Unlink from templates') . NAME_DELIMITER);
                    }
                    $result[] = array(implode(', ', zbx_objectValues($templates, 'name')), BR());
                }
                break;
            default:
        }
    } else {
        switch ($data['operationtype']) {
            case OPERATION_TYPE_MESSAGE:
                if (isset($data['opmessage']['default_msg']) && !empty($data['opmessage']['default_msg'])) {
                    if (isset($_REQUEST['def_shortdata']) && isset($_REQUEST['def_longdata'])) {
                        $result[] = array(bold(_('Subject') . NAME_DELIMITER), BR(), zbx_nl2br($_REQUEST['def_shortdata']));
                        $result[] = array(bold(_('Message') . NAME_DELIMITER), BR(), zbx_nl2br($_REQUEST['def_longdata']));
                    } elseif (isset($data['opmessage']['operationid'])) {
                        $sql = 'SELECT a.def_shortdata,a.def_longdata ' . ' FROM actions a,operations o ' . ' WHERE a.actionid=o.actionid ' . ' AND o.operationid=' . zbx_dbstr($data['operationid']);
                        if ($rows = DBfetch(DBselect($sql, 1))) {
                            $result[] = array(bold(_('Subject') . NAME_DELIMITER), BR(), zbx_nl2br($rows['def_shortdata']));
                            $result[] = array(bold(_('Message') . NAME_DELIMITER), BR(), zbx_nl2br($rows['def_longdata']));
                        }
                    }
                } else {
                    $result[] = array(bold(_('Subject') . NAME_DELIMITER), BR(), zbx_nl2br($data['opmessage']['subject']));
                    $result[] = array(bold(_('Message') . NAME_DELIMITER), BR(), zbx_nl2br($data['opmessage']['message']));
                }
                break;
            case OPERATION_TYPE_COMMAND:
                switch ($data['opcommand']['type']) {
                    case ZBX_SCRIPT_TYPE_IPMI:
                        $result[] = array(bold(_('Run IPMI command') . NAME_DELIMITER), BR(), italic(zbx_nl2br($data['opcommand']['command'])));
                        break;
                    case ZBX_SCRIPT_TYPE_SSH:
                        $result[] = array(bold(_('Run SSH commands') . NAME_DELIMITER), BR(), italic(zbx_nl2br($data['opcommand']['command'])));
                        break;
                    case ZBX_SCRIPT_TYPE_TELNET:
                        $result[] = array(bold(_('Run TELNET commands') . NAME_DELIMITER), BR(), italic(zbx_nl2br($data['opcommand']['command'])));
                        break;
                    case ZBX_SCRIPT_TYPE_CUSTOM_SCRIPT:
                        if ($data['opcommand']['execute_on'] == ZBX_SCRIPT_EXECUTE_ON_AGENT) {
                            $result[] = array(bold(_('Run custom commands on Zabbix agent') . NAME_DELIMITER), BR(), italic(zbx_nl2br($data['opcommand']['command'])));
                        } else {
                            $result[] = array(bold(_('Run custom commands on Zabbix server') . NAME_DELIMITER), BR(), italic(zbx_nl2br($data['opcommand']['command'])));
                        }
                        break;
                    case ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT:
                        $userScripts = API::Script()->get(array('scriptids' => $data['opcommand']['scriptid'], 'output' => API_OUTPUT_EXTEND));
                        $userScript = reset($userScripts);
                        $result[] = array(bold(_('Run global script') . NAME_DELIMITER), italic($userScript['name']));
                        break;
                    default:
                        $result[] = array(bold(_('Run commands') . NAME_DELIMITER), BR(), italic(zbx_nl2br($data['opcommand']['command'])));
                }
                break;
            default:
        }
    }
    return $result;
}
 $addUsrgrpBtn = new CButton('add', _('Add'), 'return PopUp("popup.php?dstfrm=action.edit&srctbl=usrgrp&srcfld1=usrgrpid&srcfld2=name&multiselect=1", 450, 450)', 'link_menu');
 $addUsrgrpBtn->attr('id', 'addusrgrpbtn');
 $usrgrpList->addRow(new CRow(new CCol($addUsrgrpBtn, null, 2), null, 'opmsgUsrgrpListFooter'));
 $userList = new CTable(null, 'formElementTable');
 $userList->setHeader(array(_('User'), _('Action')));
 $userList->attr('style', 'min-width: 310px;');
 $userList->setAttribute('id', 'opmsgUserList');
 $addUserBtn = new CButton('add', _('Add'), 'return PopUp("popup.php?dstfrm=action.edit&srctbl=users&srcfld1=userid&srcfld2=alias&multiselect=1", 450, 450)', 'link_menu');
 $addUserBtn->attr('id', 'adduserbtn');
 $userList->addRow(new CRow(new CCol($addUserBtn, null, 2), null, 'opmsgUserListFooter'));
 // add participations
 $usrgrpids = isset($this->data['new_operation']['opmessage_grp']) ? zbx_objectValues($this->data['new_operation']['opmessage_grp'], 'usrgrpid') : array();
 $userids = isset($this->data['new_operation']['opmessage_usr']) ? zbx_objectValues($this->data['new_operation']['opmessage_usr'], 'userid') : array();
 $usrgrps = API::UserGroup()->get(array('usrgrpids' => $usrgrpids, 'output' => array('name')));
 order_result($usrgrps, 'name');
 $users = API::User()->get(array('userids' => $userids, 'output' => array('alias')));
 order_result($users, 'alias');
 $jsInsert = 'addPopupValues(' . zbx_jsvalue(array('object' => 'usrgrpid', 'values' => $usrgrps)) . ');';
 $jsInsert .= 'addPopupValues(' . zbx_jsvalue(array('object' => 'userid', 'values' => $users)) . ');';
 zbx_add_post_js($jsInsert);
 $newOperationsTable->addRow(array(_('Send to User groups'), new CDiv($usrgrpList, 'objectgroup inlineblock border_dotted ui-corner-all')));
 $newOperationsTable->addRow(array(_('Send to Users'), new CDiv($userList, 'objectgroup inlineblock border_dotted ui-corner-all')));
 $mediaTypeComboBox = new CComboBox('new_operation[opmessage][mediatypeid]', $this->data['new_operation']['opmessage']['mediatypeid']);
 $mediaTypeComboBox->addItem(0, '- ' . _('All') . ' -');
 $db_mediatypes = DBselect('SELECT mt.mediatypeid,mt.description' . ' FROM media_type mt' . ' WHERE ' . DBin_node('mt.mediatypeid') . ' ORDER BY mt.description');
 while ($db_mediatype = DBfetch($db_mediatypes)) {
     $mediaTypeComboBox->addItem($db_mediatype['mediatypeid'], $db_mediatype['description']);
 }
 $newOperationsTable->addRow(array(_('Send only to'), $mediaTypeComboBox));
 $newOperationsTable->addRow(array(_('Default message'), new CCheckBox('new_operation[opmessage][default_msg]', $this->data['new_operation']['opmessage']['default_msg'], 'javascript: submit();', 1)), 'indent_top');
 if (!$this->data['new_operation']['opmessage']['default_msg']) {
Esempio n. 25
0
        }
        if (!isset($messages['triggers.recovery'])) {
            $messages['triggers.recovery'] = 0;
        }
        if (!isset($messages['triggers.severities'])) {
            $messages['triggers.severities'] = array();
        }
        DBstart();
        updateMessageSettings($messages);
        $result = API::User()->updateProfile($user);
        if ($result && CwebUser::$data['type'] > USER_TYPE_ZABBIX_USER) {
            $result = API::User()->updateMedia(array('users' => $user, 'medias' => $user['user_medias']));
        }
        $result = DBend($result);
        if (!$result) {
            error(API::User()->resetErrors());
        }
        if ($result) {
            DBstart();
            add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_USER, 'User alias [' . CWebUser::$data['alias'] . '] Name [' . CWebUser::$data['name'] . ']' . ' Surname [' . CWebUser::$data['surname'] . '] profile id [' . CWebUser::$data['userid'] . ']');
            DBend(true);
            ob_end_clean();
            redirect(CWebUser::$data['last_page']['url']);
        } else {
            show_messages($result, _('User updated'), _('Cannot update user'));
        }
    }
}
ob_end_flush();
/*
 * Display
Esempio n. 26
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     $sysmapIds = array_keys($result);
     // adding elements
     if ($options['selectSelements'] !== null && $options['selectSelements'] != API_OUTPUT_COUNT) {
         $selements = API::getApiService()->select('sysmaps_elements', ['output' => $this->outputExtend($options['selectSelements'], ['selementid', 'sysmapid']), 'filter' => ['sysmapid' => $sysmapIds], 'preservekeys' => true]);
         $relation_map = $this->createRelationMap($selements, 'sysmapid', 'selementid');
         // add selement URLs
         if ($this->outputIsRequested('urls', $options['selectSelements'])) {
             foreach ($selements as &$selement) {
                 $selement['urls'] = [];
             }
             unset($selement);
             if (!is_null($options['expandUrls'])) {
                 $dbMapUrls = DBselect('SELECT su.sysmapurlid,su.sysmapid,su.name,su.url,su.elementtype' . ' FROM sysmap_url su' . ' WHERE ' . dbConditionInt('su.sysmapid', $sysmapIds));
                 while ($mapUrl = DBfetch($dbMapUrls)) {
                     foreach ($selements as $snum => $selement) {
                         if (bccomp($selement['sysmapid'], $mapUrl['sysmapid']) == 0 && ($selement['elementtype'] == $mapUrl['elementtype'] && $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP || $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS && $mapUrl['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST)) {
                             $selements[$snum]['urls'][] = $this->expandUrlMacro($mapUrl, $selement);
                         }
                     }
                 }
             }
             $dbSelementUrls = DBselect('SELECT seu.sysmapelementurlid,seu.selementid,seu.name,seu.url' . ' FROM sysmap_element_url seu' . ' WHERE ' . dbConditionInt('seu.selementid', array_keys($selements)));
             while ($selementUrl = DBfetch($dbSelementUrls)) {
                 $selements[$selementUrl['selementid']]['urls'][] = is_null($options['expandUrls']) ? $selementUrl : $this->expandUrlMacro($selementUrl, $selements[$selementUrl['selementid']]);
             }
         }
         $selements = $this->unsetExtraFields($selements, ['sysmapid', 'selementid'], $options['selectSelements']);
         $result = $relation_map->mapMany($result, $selements, 'selements');
     }
     // adding icon maps
     if ($options['selectIconMap'] !== null && $options['selectIconMap'] != API_OUTPUT_COUNT) {
         $iconMaps = API::getApiService()->select($this->tableName(), ['output' => ['sysmapid', 'iconmapid'], 'filter' => ['sysmapid' => $sysmapIds]]);
         $relation_map = $this->createRelationMap($iconMaps, 'sysmapid', 'iconmapid');
         $iconMaps = API::IconMap()->get(['output' => $this->outputExtend($options['selectIconMap'], ['iconmapid']), 'iconmapids' => zbx_objectValues($iconMaps, 'iconmapid'), 'preservekeys' => true]);
         $iconMaps = $this->unsetExtraFields($iconMaps, ['iconmapid'], $options['selectIconMap']);
         $result = $relation_map->mapOne($result, $iconMaps, 'iconmap');
     }
     // adding links
     if ($options['selectLinks'] !== null && $options['selectLinks'] != API_OUTPUT_COUNT) {
         $links = API::getApiService()->select('sysmaps_links', ['output' => $this->outputExtend($options['selectLinks'], ['sysmapid', 'linkid']), 'filter' => ['sysmapid' => $sysmapIds], 'preservekeys' => true]);
         $relation_map = $this->createRelationMap($links, 'sysmapid', 'linkid');
         // add link triggers
         if ($this->outputIsRequested('linktriggers', $options['selectLinks'])) {
             $linkTriggers = DBFetchArrayAssoc(DBselect('SELECT DISTINCT slt.*' . ' FROM sysmaps_link_triggers slt' . ' WHERE ' . dbConditionInt('slt.linkid', $relation_map->getRelatedIds())), 'linktriggerid');
             $linkTriggerRelationMap = $this->createRelationMap($linkTriggers, 'linkid', 'linktriggerid');
             $links = $linkTriggerRelationMap->mapMany($links, $linkTriggers, 'linktriggers');
         }
         $links = $this->unsetExtraFields($links, ['sysmapid', 'linkid'], $options['selectLinks']);
         $result = $relation_map->mapMany($result, $links, 'links');
     }
     // adding urls
     if ($options['selectUrls'] !== null && $options['selectUrls'] != API_OUTPUT_COUNT) {
         $links = API::getApiService()->select('sysmap_url', ['output' => $this->outputExtend($options['selectUrls'], ['sysmapid', 'sysmapurlid']), 'filter' => ['sysmapid' => $sysmapIds], 'preservekeys' => true]);
         $relation_map = $this->createRelationMap($links, 'sysmapid', 'sysmapurlid');
         $links = $this->unsetExtraFields($links, ['sysmapid', 'sysmapurlid'], $options['selectUrls']);
         $result = $relation_map->mapMany($result, $links, 'urls');
     }
     // Adding user shares.
     if ($options['selectUsers'] !== null && $options['selectUsers'] != API_OUTPUT_COUNT) {
         $relation_map = $this->createRelationMap($result, 'sysmapid', 'userid', 'sysmap_user');
         // Get all allowed users.
         $related_users = API::User()->get(['output' => ['userid'], 'userids' => $relation_map->getRelatedIds(), 'preservekeys' => true]);
         $related_userids = zbx_objectValues($related_users, 'userid');
         if ($related_userids) {
             $users = API::getApiService()->select('sysmap_user', ['output' => $this->outputExtend($options['selectUsers'], ['sysmapid', 'userid']), 'filter' => ['sysmapid' => $sysmapIds, 'userid' => $related_userids], 'preservekeys' => true]);
             $relation_map = $this->createRelationMap($users, 'sysmapid', 'sysmapuserid');
             $users = $this->unsetExtraFields($users, ['sysmapuserid', 'userid', 'permission'], $options['selectUsers']);
             foreach ($users as &$user) {
                 unset($user['sysmapid']);
             }
             unset($user);
             $result = $relation_map->mapMany($result, $users, 'users');
         } else {
             foreach ($result as &$row) {
                 $row['users'] = [];
             }
             unset($row);
         }
     }
     // Adding user group shares.
     if ($options['selectUserGroups'] !== null && $options['selectUserGroups'] != API_OUTPUT_COUNT) {
         $relation_map = $this->createRelationMap($result, 'sysmapid', 'usrgrpid', 'sysmap_usrgrp');
         // Get all allowed groups.
         $related_groups = API::UserGroup()->get(['output' => ['usrgrpid'], 'usrgrpids' => $relation_map->getRelatedIds(), 'preservekeys' => true]);
         $related_groupids = zbx_objectValues($related_groups, 'usrgrpid');
         if ($related_groupids) {
             $user_groups = API::getApiService()->select('sysmap_usrgrp', ['output' => $this->outputExtend($options['selectUserGroups'], ['sysmapid', 'usrgrpid']), 'filter' => ['sysmapid' => $sysmapIds, 'usrgrpid' => $related_groupids], 'preservekeys' => true]);
             $relation_map = $this->createRelationMap($user_groups, 'sysmapid', 'sysmapusrgrpid');
             $user_groups = $this->unsetExtraFields($user_groups, ['sysmapusrgrpid', 'usrgrpid', 'permission'], $options['selectUserGroups']);
             foreach ($user_groups as &$user_group) {
                 unset($user_group['sysmapid']);
             }
             unset($user_group);
             $result = $relation_map->mapMany($result, $user_groups, 'userGroups');
         } else {
             foreach ($result as &$row) {
                 $row['userGroups'] = [];
             }
             unset($row);
         }
     }
     return $result;
 }
Esempio n. 27
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $sortfield = 'clock';
     $sortorder = ZBX_SORT_DOWN;
     $sorttitle = _('Time');
     switch ($this->screenitem['sort_triggers']) {
         case SCREEN_SORT_TRIGGERS_TIME_ASC:
             $sortfield = 'clock';
             $sortorder = ZBX_SORT_UP;
             $sorttitle = _('Time');
             break;
         case SCREEN_SORT_TRIGGERS_TIME_DESC:
             $sortfield = 'clock';
             $sortorder = ZBX_SORT_DOWN;
             $sorttitle = _('Time');
             break;
         case SCREEN_SORT_TRIGGERS_TYPE_ASC:
             $sortfield = 'description';
             $sortorder = ZBX_SORT_UP;
             $sorttitle = _('Type');
             break;
         case SCREEN_SORT_TRIGGERS_TYPE_DESC:
             $sortfield = 'description';
             $sortorder = ZBX_SORT_DOWN;
             $sorttitle = _('Type');
             break;
         case SCREEN_SORT_TRIGGERS_STATUS_ASC:
             $sortfield = 'status';
             $sortorder = ZBX_SORT_UP;
             $sorttitle = _('Status');
             break;
         case SCREEN_SORT_TRIGGERS_STATUS_DESC:
             $sortfield = 'status';
             $sortorder = ZBX_SORT_DOWN;
             $sorttitle = _('Status');
             break;
         case SCREEN_SORT_TRIGGERS_RECIPIENT_ASC:
             $sortfield = 'sendto';
             $sortorder = ZBX_SORT_UP;
             $sorttitle = _('Recipient(s)');
             break;
         case SCREEN_SORT_TRIGGERS_RECIPIENT_DESC:
             $sortfield = 'sendto';
             $sortorder = ZBX_SORT_DOWN;
             $sorttitle = _('Recipient(s)');
             break;
     }
     $sql = 'SELECT a.alertid,a.clock,a.sendto,a.subject,a.message,a.status,a.retries,a.error,' . 'a.userid,a.actionid,a.mediatypeid,mt.description' . ' FROM events e,alerts a' . ' LEFT JOIN media_type mt ON mt.mediatypeid=a.mediatypeid' . ' WHERE e.eventid=a.eventid' . ' AND alerttype=' . ALERT_TYPE_MESSAGE;
     if (CWebUser::getType() != USER_TYPE_SUPER_ADMIN) {
         $userid = CWebUser::$data['userid'];
         $userGroups = getUserGroupsByUserId($userid);
         $sql .= ' AND EXISTS (' . 'SELECT NULL' . ' FROM functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY f.triggerid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ')';
     }
     $sql .= ' ORDER BY ' . $sortfield . ' ' . $sortorder;
     $alerts = DBfetchArray(DBselect($sql, $this->screenitem['elements']));
     order_result($alerts, $sortfield, $sortorder);
     if ($alerts) {
         $dbUsers = API::User()->get(array('output' => array('userid', 'alias', 'name', 'surname'), 'userids' => zbx_objectValues($alerts, 'userid'), 'preservekeys' => true));
     }
     // indicator of sort field
     $sortfieldSpan = new CSpan(array($sorttitle, SPACE));
     $sortorderSpan = new CSpan(SPACE, $sortorder === ZBX_SORT_DOWN ? 'icon_sortdown default_cursor' : 'icon_sortup default_cursor');
     // create alert table
     $actionTable = new CTableInfo(_('No action log entries found.'));
     $actionTable->setHeader(array($sortfield === 'clock' ? array($sortfieldSpan, $sortorderSpan) : _('Time'), _('Action'), $sortfield === 'description' ? array($sortfieldSpan, $sortorderSpan) : _('Type'), $sortfield === 'sendto' ? array($sortfieldSpan, $sortorderSpan) : _('Recipient(s)'), _('Message'), $sortfield === 'status' ? array($sortfieldSpan, $sortorderSpan) : _('Status'), _('Info')));
     $actions = API::Action()->get(array('output' => array('actionid', 'name'), 'actionids' => array_unique(zbx_objectValues($alerts, 'actionid')), 'preservekeys' => true));
     foreach ($alerts as $alert) {
         if ($alert['status'] == ALERT_STATUS_SENT) {
             $status = new CSpan(_('Sent'), 'green');
         } elseif ($alert['status'] == ALERT_STATUS_NOT_SENT) {
             $status = new CSpan(array(_('In progress') . ':', BR(), _n('%1$s retry left', '%1$s retries left', ALERT_MAX_RETRIES - $alert['retries'])), 'orange');
         } else {
             $status = new CSpan(_('Not sent'), 'red');
         }
         $recipient = $alert['userid'] ? array(bold(getUserFullname($dbUsers[$alert['userid']])), BR(), $alert['sendto']) : $alert['sendto'];
         $message = array(bold(_('Subject') . ':'), br(), $alert['subject'], br(), br(), bold(_('Message') . ':'), br(), $alert['message']);
         if (zbx_empty($alert['error'])) {
             $info = '';
         } else {
             $info = new CDiv(SPACE, 'status_icon iconerror');
             $info->setHint($alert['error'], 'on');
         }
         $actionTable->addRow(array(new CCol(zbx_date2str(DATE_TIME_FORMAT_SECONDS, $alert['clock']), 'top'), new CCol($actions[$alert['actionid']]['name'], 'top'), new CCol($alert['mediatypeid'] == 0 ? '-' : $alert['description'], 'top'), new CCol($recipient, 'top'), new CCol($message, 'top pre'), new CCol($status, 'top'), new CCol($info, 'wraptext top')));
     }
     return $this->getOutput($actionTable);
 }
Esempio n. 28
0
    $data['form'] = get_request('form');
    $data['form_refresh'] = get_request('form_refresh', 0);
    // render view
    $usersView = new CView('administration.users.edit', $data);
    $usersView->render();
    $usersView->show();
} else {
    // get user groups
    $options = array('output' => API_OUTPUT_EXTEND, 'sortfield' => 'name');
    $data['userGroups'] = API::UserGroup()->get($options);
    // get users
    $options = array('output' => API_OUTPUT_EXTEND, 'selectUsrgrps' => API_OUTPUT_EXTEND, 'getAccess' => 1, 'limit' => $config['search_limit'] + 1);
    if ($_REQUEST['filter_usrgrpid'] > 0) {
        $options['usrgrpids'] = $_REQUEST['filter_usrgrpid'];
    }
    $data['users'] = API::User()->get($options);
    // sort users
    order_result($data['users'], getPageSortField('alias'), getPageSortOrder());
    $data['paging'] = getPagingLine($data['users']);
    // set default lastaccess time to 0
    foreach ($data['users'] as $user) {
        $data['usersSessions'][$user['userid']] = array('lastaccess' => 0);
    }
    $sql = 'SELECT s.userid,MAX(s.lastaccess) AS lastaccess,s.status' . ' FROM sessions s' . ' WHERE ' . dbConditionInt('s.userid', zbx_objectValues($data['users'], 'userid')) . ' GROUP BY s.userid,s.status';
    $db_sessions = DBselect($sql);
    while ($session = DBfetch($db_sessions)) {
        if ($data['usersSessions'][$session['userid']]['lastaccess'] < $session['lastaccess']) {
            $data['usersSessions'][$session['userid']] = $session;
        }
    }
    // render view
Esempio n. 29
0
 public function validateOperations($operations)
 {
     $operations = zbx_toArray($operations);
     foreach ($operations as $operation) {
         if ((isset($operation['esc_step_from']) || isset($operation['esc_step_to'])) && !isset($operation['esc_step_from'], $operation['esc_step_to'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('esc_step_from and esc_step_to must be set together.'));
         }
         if (isset($operation['esc_step_from'], $operation['esc_step_to'])) {
             if ($operation['esc_step_from'] < 1 || $operation['esc_step_to'] < 0) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation escalation step values.'));
             }
             if ($operation['esc_step_from'] > $operation['esc_step_to'] && $operation['esc_step_to'] != 0) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation escalation step values.'));
             }
         }
         if (isset($operation['esc_period'])) {
             if (isset($operation['esc_period']) && $operation['esc_period'] != 0 && $operation['esc_period'] < SEC_PER_MIN) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation step duration.'));
             }
         }
         $hostIdsAll = $hostGroupIdsAll = $useridsAll = $userGroupidsAll = array();
         switch ($operation['operationtype']) {
             case OPERATION_TYPE_MESSAGE:
                 $userids = isset($operation['opmessage_usr']) ? zbx_objectValues($operation['opmessage_usr'], 'userid') : array();
                 $usergroupids = isset($operation['opmessage_grp']) ? zbx_objectValues($operation['opmessage_grp'], 'usrgrpid') : array();
                 if (empty($userids) && empty($usergroupids)) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No recipients for action operation message.'));
                 }
                 $useridsAll = array_merge($useridsAll, $userids);
                 $userGroupidsAll = array_merge($userGroupidsAll, $usergroupids);
                 break;
             case OPERATION_TYPE_COMMAND:
                 if (!isset($operation['opcommand']['type'])) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No command type specified for action operation.'));
                 }
                 if ((!isset($operation['opcommand']['command']) || zbx_empty(trim($operation['opcommand']['command']))) && $operation['opcommand']['type'] != ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('No command specified for action operation.'));
                 }
                 switch ($operation['opcommand']['type']) {
                     case ZBX_SCRIPT_TYPE_IPMI:
                         break;
                     case ZBX_SCRIPT_TYPE_CUSTOM_SCRIPT:
                         if (!isset($operation['opcommand']['execute_on'])) {
                             self::exception(ZBX_API_ERROR_PARAMETERS, _s('No execution target specified for action operation command "%s".', $operation['opcommand']['command']));
                         }
                         break;
                     case ZBX_SCRIPT_TYPE_SSH:
                         if (!isset($operation['opcommand']['authtype']) || zbx_empty($operation['opcommand']['authtype'])) {
                             self::exception(ZBX_API_ERROR_PARAMETERS, _s('No authentication type specified for action operation command "%s".', $operation['opcommand']['command']));
                         }
                         if (!isset($operation['opcommand']['username']) || zbx_empty($operation['opcommand']['username'])) {
                             self::exception(ZBX_API_ERROR_PARAMETERS, _s('No authentication user name specified for action operation command "%s".', $operation['opcommand']['command']));
                         }
                         if ($operation['opcommand']['authtype'] == ITEM_AUTHTYPE_PUBLICKEY) {
                             if (!isset($operation['opcommand']['publickey']) || zbx_empty($operation['opcommand']['publickey'])) {
                                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('No public key file specified for action operation command "%s".', $operation['opcommand']['command']));
                             }
                             if (!isset($operation['opcommand']['privatekey']) || zbx_empty($operation['opcommand']['privatekey'])) {
                                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('No private key file specified for action operation command "%s".', $operation['opcommand']['command']));
                             }
                         }
                         break;
                     case ZBX_SCRIPT_TYPE_TELNET:
                         if (!isset($operation['opcommand']['username']) || zbx_empty($operation['opcommand']['username'])) {
                             self::exception(ZBX_API_ERROR_PARAMETERS, _s('No authentication user name specified for action operation command "%s".', $operation['opcommand']['command']));
                         }
                         break;
                     case ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT:
                         if (!isset($operation['opcommand']['scriptid']) || zbx_empty($operation['opcommand']['scriptid'])) {
                             self::exception(ZBX_API_ERROR_PARAMETERS, _('No script specified for action operation command.'));
                         }
                         $scripts = API::Script()->get(array('output' => array('scriptid', 'name'), 'scriptids' => $operation['opcommand']['scriptid'], 'preservekeys' => true));
                         if (!isset($scripts[$operation['opcommand']['scriptid']])) {
                             self::exception(ZBX_API_ERROR_PARAMETERS, _('Specified script does not exist or you do not have rights on it for action operation command.'));
                         }
                         break;
                     default:
                         self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation command type.'));
                 }
                 if (isset($operation['opcommand']['port']) && !zbx_empty($operation['opcommand']['port'])) {
                     if (zbx_ctype_digit($operation['opcommand']['port'])) {
                         if ($operation['opcommand']['port'] > 65535 || $operation['opcommand']['port'] < 1) {
                             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect action operation port "%s".', $operation['opcommand']['port']));
                         }
                     } elseif (!preg_match('/^' . ZBX_PREG_EXPRESSION_USER_MACROS . '$/', $operation['opcommand']['port'])) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect action operation port "%s".', $operation['opcommand']['port']));
                     }
                 }
                 $groupids = array();
                 if (isset($operation['opcommand_grp'])) {
                     $groupids = zbx_objectValues($operation['opcommand_grp'], 'groupid');
                 }
                 $hostids = array();
                 $withoutCurrent = true;
                 if (isset($operation['opcommand_hst'])) {
                     foreach ($operation['opcommand_hst'] as $hstCommand) {
                         if ($hstCommand['hostid'] == 0) {
                             $withoutCurrent = false;
                         } else {
                             $hostids[$hstCommand['hostid']] = $hstCommand['hostid'];
                         }
                     }
                 }
                 if (empty($groupids) && empty($hostids) && $withoutCurrent) {
                     if ($operation['opcommand']['type'] == ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('You did not specify targets for action operation global script "%s".', $scripts[$operation['opcommand']['scriptid']]['name']));
                     } else {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('You did not specify targets for action operation command "%s".', $operation['opcommand']['command']));
                     }
                 }
                 $hostIdsAll = array_merge($hostIdsAll, $hostids);
                 $hostGroupIdsAll = array_merge($hostGroupIdsAll, $groupids);
                 break;
             case OPERATION_TYPE_GROUP_ADD:
             case OPERATION_TYPE_GROUP_REMOVE:
                 $groupids = isset($operation['opgroup']) ? zbx_objectValues($operation['opgroup'], 'groupid') : array();
                 if (empty($groupids)) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('Operation has no group to operate.'));
                 }
                 $hostGroupIdsAll = array_merge($hostGroupIdsAll, $groupids);
                 break;
             case OPERATION_TYPE_TEMPLATE_ADD:
             case OPERATION_TYPE_TEMPLATE_REMOVE:
                 $templateids = isset($operation['optemplate']) ? zbx_objectValues($operation['optemplate'], 'templateid') : array();
                 if (empty($templateids)) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('Operation has no template to operate.'));
                 }
                 $hostIdsAll = array_merge($hostIdsAll, $templateids);
                 break;
             case OPERATION_TYPE_HOST_ADD:
             case OPERATION_TYPE_HOST_REMOVE:
             case OPERATION_TYPE_HOST_ENABLE:
             case OPERATION_TYPE_HOST_DISABLE:
                 break;
             default:
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation type.'));
         }
     }
     if (!API::HostGroup()->isWritable($hostGroupIdsAll)) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation host group. Host group does not exist or you have no access to this host group.'));
     }
     if (!API::Host()->isWritable($hostIdsAll)) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation host. Host does not exist or you have no access to this host.'));
     }
     if (!API::User()->isReadable($useridsAll)) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation user. User does not exist or you have no access to this user.'));
     }
     if (!API::UserGroup()->isReadable($userGroupidsAll)) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect action operation user group. User group does not exist or you have no access to this user group.'));
     }
     return true;
 }
Esempio n. 30
0
 /**
  * Delete user.
  *
  * @param array $userids
  *
  * @return array
  */
 public function delete(array $userids)
 {
     $this->validateDelete($userids);
     // Get users for audit log.
     $db_users = API::User()->get(['output' => ['alias', 'name', 'surname'], 'userids' => $userids]);
     // Delete action operation msg.
     $db_operations = DBFetchArray(DBselect('SELECT DISTINCT om.operationid' . ' FROM opmessage_usr om' . ' WHERE ' . dbConditionInt('om.userid', $userids)));
     DB::delete('opmessage_usr', ['userid' => $userids]);
     // Delete empty operations.
     $del_operations = DBFetchArray(DBselect('SELECT DISTINCT o.operationid,o.actionid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', zbx_objectValues($db_operations, 'operationid')) . ' AND NOT EXISTS(SELECT NULL FROM opmessage_grp omg WHERE omg.operationid=o.operationid)' . ' AND NOT EXISTS(SELECT NULL FROM opmessage_usr omu WHERE omu.operationid=o.operationid)'));
     DB::delete('operations', ['operationid' => zbx_objectValues($del_operations, 'operationid')]);
     DB::delete('media', ['userid' => $userids]);
     DB::delete('profiles', ['userid' => $userids]);
     DB::delete('users_groups', ['userid' => $userids]);
     DB::delete('users', ['userid' => $userids]);
     $actionids = zbx_objectValues($del_operations, 'actionid');
     if ($actionids) {
         $this->disableActionsWithoutOperations($actionids);
     }
     // Audit log.
     foreach ($db_users as $db_user) {
         add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_USER, 'User alias [' . $db_user['alias'] . '] name [' . $db_user['name'] . '] surname [' . $db_user['surname'] . ']');
     }
     return ['userids' => $userids];
 }