Id()) {
ZM\Warning('Group not found for save');
$error_message .= 'Group not found.
';
$view = 'groups';
return;
}
$new_ids = isset($_REQUEST['newGroup']['MonitorIds']) ? array_map('intval', array_filter((array)$_REQUEST['newGroup']['MonitorIds'], 'is_scalar')) : array();
$old_ids = $group->Id() ? dbFetchAll('SELECT `MonitorId` FROM `Groups_Monitors` WHERE `GroupId`=?', 'MonitorId', array($group->Id())) : array();
$moved = array_merge(array_diff($old_ids, $new_ids), array_diff($new_ids, $old_ids));
$new_parent = (($_REQUEST['newGroup']['ParentId'] ?? '') == '' ? null : $_REQUEST['newGroup']['ParentId']);
$raw_name = $_REQUEST['newGroup']['Name'] ?? '';
$new_name = is_array($raw_name) ? '' : trim((string)$raw_name);
if ($new_name === '') {
ZM\Warning('Group save with empty name for group '.$group->Id());
$error_message .= 'A group needs a name.
';
$view = 'groups';
return;
}
// The group modal posts view=group, which has no view file, so failures are
// shown on the Groups page; otherwise index.php sends the user to the console.
if (!ZM\Group::validParent($group->Id(), $new_parent)) {
ZM\Warning('Invalid parent group for group '.$group->Id());
$error_message .= 'A group cannot be placed under itself or one of its own groups.
';
$view = 'groups';
return;
}
// Re-parenting moves every monitor of this group and its children between ancestors.
if ($group->Id() and ($new_parent != $group->ParentId())) $moved = array_merge($moved, $group->MonitorIds());
if (!ZM\Group::canEditMembership($moved)) {
ZM\Warning('Need edit permission on every monitor moved into or out of a group');
$error_message .= 'You need edit permission on every monitor moved into or out of the group.
';
$view = 'groups';
return;
}
if (!$group->save(
array(
'Name'=> $new_name,
'ParentId'=>$new_parent,
)
)) {
$error_message .= validHtmlStr($group->get_last_error());
$view = 'groups';
return;
}
$group_id = $group->Id();
if (dbQuery('DELETE FROM `Groups_Monitors` WHERE `GroupId`=?', array($group_id)) === NULL) {
$error_message .= 'Error clearing group monitors: '.htmlspecialchars(dbLastError()).'
';
$view = 'groups';
return;
}
if ($group_id and isset($_REQUEST['newGroup']['MonitorIds'])) {
$failed = false;
foreach ( $new_ids as $mid ) {
if (dbQuery('INSERT INTO `Groups_Monitors` (`GroupId`,`MonitorId`) VALUES (?,?)', array($group_id, $mid)) === NULL) {
$error_message .= 'Error adding monitor '.$mid.' to group: '.htmlspecialchars(dbLastError()).'
';
$failed = true;
break;
}
}
if ($failed) {
$view = 'groups';
return;
}
}
ZM\AuditAction((!empty($_REQUEST['gid']) ? 'update' : 'create'), 'group', $group->Id(), 'Name: '.$_REQUEST['newGroup']['Name']);
$redirect = '?view=groups';
}
?>