function msgRaidDelete($aRequest)
{
    if (validRaidlead()) {
        $Connector = Connector::getInstance();
        // Call plugins
        $RaidId = intval($aRequest['id']);
        PluginRegistry::ForEachPlugin(function ($PluginInstance) use($RaidId) {
            $PluginInstance->onRaidRemove($RaidId);
        });
        do {
            // Delete raid
            $Connector->beginTransaction();
            $DeleteRaidQuery = $Connector->prepare('DELETE FROM `' . RP_TABLE_PREFIX . 'Raid` WHERE RaidId = :RaidId LIMIT 1');
            $DeleteRaidQuery->bindValue(':RaidId', $aRequest['id'], PDO::PARAM_INT);
            if (!$DeleteRaidQuery->execute()) {
                $Connector->rollBack();
                return;
                // ### return, error ###
            }
            // Delete attendance
            $DeleteAttendanceQuery = $Connector->prepare('DELETE FROM `' . RP_TABLE_PREFIX . 'Attendance` WHERE RaidId = :RaidId');
            $DeleteAttendanceQuery->bindValue(':RaidId', $aRequest['id'], PDO::PARAM_INT);
            if (!$DeleteAttendanceQuery->execute()) {
                $Connector->rollBack();
                return;
                // ### return, error ###
            }
        } while (!$Connector->commit());
        $Session = Session::get();
        $ShowMonth = isset($Session['Calendar']) && isset($Session['Calendar']['month']) ? $Session['Calendar']['month'] : $aRequest['month'];
        $ShowYear = isset($Session['Calendar']) && isset($Session['Calendar']['year']) ? $Session['Calendar']['year'] : $aRequest['year'];
        msgQueryCalendar(prepareCalRequest($ShowMonth, $ShowYear));
    } else {
        $Out = Out::getInstance();
        $Out->pushError(L('AccessDenied'));
    }
}
function msgRaidCreate($aRequest)
{
    if (validRaidlead()) {
        global $gGame;
        loadGameSettings();
        $Connector = Connector::getInstance();
        $LocationId = $aRequest['locationId'];
        // Create location
        if ($LocationId == 0) {
            $NewLocationQuery = $Connector->prepare('INSERT INTO `' . RP_TABLE_PREFIX . 'Location`' . '(Game, Name, Image) VALUES (:Game, :Name, :Image)');
            $NewLocationQuery->bindValue(':Name', requestToXML($aRequest['locationName'], ENT_COMPAT, 'UTF-8'), PDO::PARAM_STR);
            $NewLocationQuery->bindValue(':Image', $aRequest['raidImage'], PDO::PARAM_STR);
            $NewLocationQuery->bindValue(':Game', $gGame['GameId'], PDO::PARAM_STR);
            if (!$NewLocationQuery->execute()) {
                return;
            }
            // ### return, location could not be created ###
            $LocationId = $Connector->lastInsertId();
        }
        // Create raid
        if ($LocationId != 0) {
            // First raid time calculation
            $StartHour = intval($aRequest['startHour']);
            $StartMinute = intval($aRequest['startMinute']);
            $StartDay = intval($aRequest['startDay']);
            $StartMonth = intval($aRequest['startMonth']);
            $StartYear = intval($aRequest['startYear']);
            $EndHour = intval($aRequest['endHour']);
            $EndMinute = intval($aRequest['endMinute']);
            $EndDay = intval($aRequest['endDay']);
            $EndMonth = intval($aRequest['endMonth']);
            $EndYear = intval($aRequest['endYear']);
            // Get users on vacation
            $UserSettingsQuery = $Connector->prepare('SELECT UserId, Name, IntValue, TextValue FROM `' . RP_TABLE_PREFIX . 'UserSetting` ' . 'WHERE Name = "VacationStart" OR Name = "VacationEnd" OR Name = "VacationMessage" ORDER BY UserId');
            $VactionUsers = array();
            $UserSettingsQuery->loop(function ($Settings) use(&$VactionUsers) {
                if (!isset($VactionUsers[$Settings['UserId']])) {
                    $VactionUsers[$Settings['UserId']] = array('Message' => '');
                }
                switch ($Settings['Name']) {
                    case 'VacationStart':
                        $VactionUsers[$Settings['UserId']]['Start'] = $Settings['IntValue'];
                        break;
                    case 'VacationEnd':
                        $VactionUsers[$Settings['UserId']]['End'] = $Settings['IntValue'];
                        break;
                    case 'VacationMessage':
                        $VactionUsers[$Settings['UserId']]['Message'] = $Settings['TextValue'];
                        break;
                    default:
                        break;
                }
            });
            // Prepare posting raids to forum
            $PostTargets = array();
            PluginRegistry::ForEachBinding(function ($PluginInstance) use(&$PostTargets) {
                if ($PluginInstance->isActive() && $PluginInstance->postRequested()) {
                    array_push($PostTargets, $PluginInstance);
                }
            });
            $LocationData = null;
            if (count($PostTargets) > 0) {
                loadSiteSettings();
                $LocationQuery = $Connector->prepare('SELECT * FROM `' . RP_TABLE_PREFIX . 'Location` WHERE LocationId = :LocationId LIMIT 1');
                $LocationQuery->bindValue(':LocationId', $LocationId, PDO::PARAM_INT);
                $LocationData = $LocationQuery->fetchFirst();
            }
            // Get opt-out list or auto attend users
            $AutoAttendUsers = array();
            if (strtolower($aRequest['mode'] == 'optout')) {
                $UserQuery = $Connector->prepare('SELECT UserId, CharacterId, Class, Role1 FROM `' . RP_TABLE_PREFIX . 'User` ' . 'LEFT JOIN `' . RP_TABLE_PREFIX . 'Character` USING(UserId) ' . 'WHERE Mainchar="true" AND Game=:Game');
                $UserQuery->bindValue(':Game', $gGame['GameId'], PDO::PARAM_STR);
                $UserQuery->loop(function ($aUser) use(&$AutoAttendUsers) {
                    array_push($AutoAttendUsers, $aUser);
                });
            } else {
                $UserQuery = $Connector->prepare('SELECT UserId, CharacterId, Class, Role1 FROM `' . RP_TABLE_PREFIX . 'UserSetting` ' . 'LEFT JOIN `' . RP_TABLE_PREFIX . 'Character` USING(UserId) ' . 'WHERE `' . RP_TABLE_PREFIX . 'UserSetting`.Name="AutoAttend" AND Mainchar="true" AND Game=:Game');
                $UserQuery->bindValue(':Game', $gGame['GameId'], PDO::PARAM_STR);
                $UserQuery->loop(function ($aUser) use(&$AutoAttendUsers) {
                    array_push($AutoAttendUsers, $aUser);
                });
            }
            // Create raids(s)
            $Repeat = max(0, intval($aRequest['repeat'])) + 1;
            // repeat at least once
            $GroupInfo = $gGame['Groups'][$aRequest['locationSize']];
            $SlotRoles = implode(':', array_keys($GroupInfo));
            $SlotCount = implode(':', $GroupInfo);
            $RaidMode = $aRequest['mode'] == 'optout' ? 'manual' : $aRequest['mode'];
            for ($rc = 0; $rc < $Repeat; ++$rc) {
                $NewRaidQuery = $Connector->prepare('INSERT INTO `' . RP_TABLE_PREFIX . 'Raid` ' . '(LocationId, Size, Start, End, Mode, Description, SlotRoles, SlotCount ) ' . 'VALUES (:LocationId, :Size, FROM_UNIXTIME(:Start), FROM_UNIXTIME(:End), :Mode, :Description, ' . ':SlotRoles, :SlotCount)');
                $StartDateTime = mktime($StartHour, $StartMinute, 0, $StartMonth, $StartDay, $StartYear);
                $EndDateTime = mktime($EndHour, $EndMinute, 0, $EndMonth, $EndDay, $EndYear);
                // Convert to UTC
                $StartDateTime += $aRequest['startOffset'] * 60;
                $EndDateTime += $aRequest['endOffset'] * 60;
                $NewRaidQuery->bindValue(':LocationId', $LocationId, PDO::PARAM_INT);
                $NewRaidQuery->bindValue(':Size', $aRequest['locationSize'], PDO::PARAM_INT);
                $NewRaidQuery->bindValue(':Start', $StartDateTime, PDO::PARAM_INT);
                $NewRaidQuery->bindValue(':End', $EndDateTime, PDO::PARAM_INT);
                $NewRaidQuery->bindValue(':Mode', $RaidMode, PDO::PARAM_STR);
                $NewRaidQuery->bindValue(':Description', requestToXML($aRequest['description'], ENT_COMPAT, 'UTF-8'), PDO::PARAM_STR);
                $NewRaidQuery->bindValue(':SlotRoles', $SlotRoles, PDO::PARAM_STR);
                $NewRaidQuery->bindValue(':SlotCount', $SlotCount, PDO::PARAM_STR);
                $NewRaidQuery->execute();
                $RaidId = $Connector->lastInsertId();
                // Attend players when mode is optout
                if (count($AutoAttendUsers > 0)) {
                    $Status = $RaidMode == 'all' || $RaidMode == 'attend' ? 'ok' : 'available';
                    foreach ($AutoAttendUsers as $User) {
                        $UserId = intval($User['UserId']);
                        if (isset($VactionUsers[$UserId]) && ($StartDateTime >= $VactionUsers[$UserId]['Start'] && $StartDateTime <= $VactionUsers[$UserId]['End'])) {
                            continue;
                            // ### continue, user is on vacation ###
                        }
                        $Classes = explode(':', $User['Class']);
                        $ClassId = $Classes[0];
                        $RoleId = $gGame['ClassMode'] == 'multi' ? $gGame['Classes'][$ClassId]['roles'][0] : $User['Role1'];
                        $AttendQuery = $Connector->prepare('INSERT INTO `' . RP_TABLE_PREFIX . 'Attendance` (UserId, RaidId, CharacterId, Class, Role, Status) ' . 'VALUES (:UserId, :RaidId, :CharId, :Class, :Role, :Status)');
                        $AttendQuery->bindValue(':UserId', $UserId, PDO::PARAM_INT);
                        $AttendQuery->bindValue(':RaidId', $RaidId, PDO::PARAM_INT);
                        $AttendQuery->bindValue(':CharId', $User['CharacterId'], PDO::PARAM_INT);
                        $AttendQuery->bindValue(':Class', $ClassId, PDO::PARAM_STR);
                        $AttendQuery->bindValue(':Role', $RoleId, PDO::PARAM_STR);
                        $AttendQuery->bindValue(':Status', $Status, PDO::PARAM_STR);
                        $AttendQuery->execute();
                    }
                    if ($RaidMode == 'attend') {
                        removeOverbooked($RaidId, $SlotRoles, $SlotCount);
                    }
                }
                // Set vacation attendances
                foreach ($VactionUsers as $UserId => $Settings) {
                    if ($StartDateTime >= $Settings['Start'] && $StartDateTime <= $Settings['End']) {
                        $AbsentQuery = $Connector->prepare('INSERT INTO `' . RP_TABLE_PREFIX . 'Attendance` (UserId, RaidId, Status, Comment) ' . 'VALUES (:UserId, :RaidId, "unavailable", :Message)');
                        $AbsentQuery->bindValue(':UserId', $UserId, PDO::PARAM_INT);
                        $AbsentQuery->bindValue(':RaidId', $RaidId, PDO::PARAM_INT);
                        $AbsentQuery->bindValue(':Message', $Settings['Message'], PDO::PARAM_STR);
                        $AbsentQuery->execute();
                    }
                }
                // Post raids to forum
                if (count($PostTargets) > 0) {
                    $RaidQuery = $Connector->prepare('SELECT * FROM `' . RP_TABLE_PREFIX . 'Raid` WHERE RaidId=:RaidId LIMIT 1');
                    $RaidQuery->bindValue(':RaidId', $RaidId, PDO::PARAM_INT);
                    $RaidData = $RaidQuery->fetchFirst();
                    $MessageData = Binding::generateMessage($RaidData, $LocationData);
                    try {
                        foreach ($PostTargets as $PluginInstance) {
                            $PluginInstance->post($MessageData['subject'], $MessageData['message']);
                        }
                    } catch (PDOException $Exception) {
                        Out::getInstance()->pushError($Exception->getMessage());
                    }
                }
                // Call plugins
                PluginRegistry::ForEachPlugin(function ($PluginInstance) use($RaidId) {
                    $PluginInstance->onRaidCreate($RaidId);
                });
                // Increment start/end
                switch ($aRequest['stride']) {
                    case 'day':
                        ++$StartDay;
                        ++$EndDay;
                        break;
                    case 'week':
                        $StartDay += 7;
                        $EndDay += 7;
                        break;
                    case 'month':
                        ++$StartMonth;
                        ++$EndMonth;
                        break;
                    default:
                    case 'once':
                        $rc = $Repeat;
                        // Force done
                        break;
                }
            }
            // reload calendar
            $Session = Session::get();
            $ShowMonth = isset($Session['Calendar']) && isset($Session['Calendar']['month']) ? $Session['Calendar']['month'] : $aRequest['month'];
            $ShowYear = isset($Session['Calendar']) && isset($Session['Calendar']['year']) ? $Session['Calendar']['year'] : $aRequest['year'];
            msgQueryCalendar(prepareCalRequest($ShowMonth, $ShowYear));
        }
    } else {
        $Out = Out::getInstance();
        $Out->pushError(L('AccessDenied'));
    }
}
function msgRaidupdate($aRequest)
{
    if (validRaidlead()) {
        global $gGame;
        loadGameSettings();
        $Connector = Connector::getInstance();
        // The whole update is packed into one transaction.
        // The transaction will be rolled back upon error so no half-updated
        // data is stored in the database. This requires the database to
        // support transactions.
        do {
            $Connector->beginTransaction();
            $LocationId = $aRequest['locationId'];
            // Insert new location if necessary
            if ($LocationId == 0) {
                $NewLocationQuery = $Connector->prepare('INSERT INTO `' . RP_TABLE_PREFIX . 'Location`' . '(Name, Game, Image) VALUES (:Name, :Game, :Image)');
                $NewLocationQuery->bindValue(':Name', requestToXML($aRequest['locationName'], ENT_COMPAT, 'UTF-8'), PDO::PARAM_STR);
                $NewLocationQuery->bindValue(':Game', $gGame['GameId'], PDO::PARAM_STR);
                $NewLocationQuery->bindValue(':Image', $aRequest['raidImage'], PDO::PARAM_STR);
                if (!$NewLocationQuery->execute()) {
                    $Connector->rollBack();
                    return;
                    // ### return, error ###
                }
                $LocationId = $Connector->lastInsertId();
            }
            // Update raid
            $UpdateRaidQuery = $Connector->prepare('UPDATE `' . RP_TABLE_PREFIX . 'Raid` SET ' . 'LocationId = :LocationId, Size = :Size, ' . 'Stage = :Stage, ' . 'Start = FROM_UNIXTIME(:Start), End = FROM_UNIXTIME(:End), ' . 'Description = :Description, ' . 'Mode = :Mode, ' . 'SlotRoles = :SlotRoles, SlotCount = :SlotCount ' . 'WHERE RaidId = :RaidId');
            $StartDateTime = mktime(intval($aRequest['startHour']), intval($aRequest['startMinute']), 0, intval($aRequest['startMonth']), intval($aRequest['startDay']), intval($aRequest['startYear']));
            $EndDateTime = mktime(intval($aRequest['endHour']), intval($aRequest['endMinute']), 0, intval($aRequest['endMonth']), intval($aRequest['endDay']), intval($aRequest['endYear']));
            // Convert to UTC
            $StartDateTime += $aRequest['startOffset'] * 60;
            $EndDateTime += $aRequest['endOffset'] * 60;
            $UpdateRaidQuery->bindValue(':RaidId', $aRequest['id'], PDO::PARAM_INT);
            $UpdateRaidQuery->bindValue(':LocationId', $LocationId, PDO::PARAM_INT);
            $UpdateRaidQuery->bindValue(':Stage', $aRequest['stage'], PDO::PARAM_STR);
            $UpdateRaidQuery->bindValue(':Size', $aRequest['locationSize'], PDO::PARAM_INT);
            $UpdateRaidQuery->bindValue(':Start', $StartDateTime, PDO::PARAM_INT);
            $UpdateRaidQuery->bindValue(':End', $EndDateTime, PDO::PARAM_INT);
            $UpdateRaidQuery->bindValue(':Mode', $aRequest['mode'], PDO::PARAM_STR);
            $UpdateRaidQuery->bindValue(':Description', requestToXML($aRequest['description'], ENT_COMPAT, 'UTF-8'), PDO::PARAM_STR);
            $UpdateRaidQuery->bindValue(':SlotRoles', implode(':', $aRequest['slotRoles']), PDO::PARAM_STR);
            $UpdateRaidQuery->bindValue(':SlotCount', implode(':', $aRequest['slotCount']), PDO::PARAM_STR);
            if (!$UpdateRaidQuery->execute()) {
                $Connector->rollBack();
                return;
                // ### return, error ###
            }
            // Remove the attends marked for delete.
            // Only random player attends can be removed.
            $NumRemoved = isset($aRequest['removed']) ? count($aRequest['removed']) : 0;
            for ($i = 0; $i < $NumRemoved; ++$i) {
                $RemoveSlot = $Connector->prepare('DELETE FROM `' . RP_TABLE_PREFIX . 'Attendance` ' . 'WHERE AttendanceId = :AttendanceId AND CharacterId = 0 AND UserId = 0');
                $RemoveSlot->bindValue(':AttendanceId', $aRequest['removed'][$i], PDO::PARAM_INT);
                if (!$RemoveSlot->execute()) {
                    $Connector->rollBack();
                    return;
                    // ### return, error ###
                }
            }
            // Now iterate over all role lists and update the players in it
            // Random player will be converted to 'real' player, i.e. they loose their
            // negative pseudo-id.
            foreach ($gGame['Roles'] as $Role) {
                if (isset($aRequest['role_' . $Role['id']])) {
                    $NumAttends = 0;
                    $AttendsForRole = $aRequest['role_' . $Role['id']];
                    // Attendances are passed in the form [id,status,id,status, … ]
                    // So we iterate with a stride of 2
                    for ($AttendIdx = 0; $AttendIdx < count($AttendsForRole);) {
                        $UpdateSlot = null;
                        // $Id = UserId when not having an attendance record
                        // $Id = AttendanceId for all others
                        $Id = intVal($AttendsForRole[$AttendIdx++]);
                        $Status = $AttendsForRole[$AttendIdx++];
                        $OldTimestamp = $AttendsForRole[$AttendIdx++];
                        $Flags = intVal($AttendsForRole[$AttendIdx++]);
                        if ($Status == 'undecided') {
                            continue;
                        }
                        // ### continue, skip undecided ###
                        // Get extra parameters
                        if (($Flags & PlayerFlagCharId) != 0) {
                            $CharId = intval($AttendsForRole[$AttendIdx++]);
                            $ActiveClass = $AttendsForRole[$AttendIdx++];
                        }
                        if (($Flags & PlayerFlagUserId) != 0) {
                            $UserId = intVal($AttendsForRole[$AttendIdx++]);
                        }
                        if (($Flags & PlayerFlagName) != 0) {
                            $Name = $AttendsForRole[$AttendIdx++];
                        }
                        if (($Flags & PlayerFlagComment) != 0) {
                            $Comment = $AttendsForRole[$AttendIdx++];
                        }
                        if (($Flags & PlayerFlagNew) != 0) {
                            // New entries
                            if (($Flags & PlayerFlagComment) != 0 && ($Flags & PlayerFlagUserId) != 0 && ($Flags & PlayerFlagCharId) != 0) {
                                // Undecided set-up
                                $UpdateSlot = $Connector->prepare('INSERT INTO `' . RP_TABLE_PREFIX . 'Attendance` ' . '( CharacterId, Class, UserId, RaidId, Status, Role, Comment ) ' . 'VALUES ( :CharId, :Class, :UserId, :RaidId, :Status, :Role, :Comment )');
                                $UpdateSlot->bindValue(':CharId', $CharId, PDO::PARAM_INT);
                                $UpdateSlot->bindValue(':Class', $ActiveClass, PDO::PARAM_STR);
                                $UpdateSlot->bindValue(':UserId', $UserId, PDO::PARAM_INT);
                                $UpdateSlot->bindValue(':Comment', $Comment, PDO::PARAM_STR);
                            } else {
                                if (($Flags & PlayerFlagComment) != 0 && ($Flags & PlayerFlagCharId) != 0) {
                                    // Undecied absent
                                    $UpdateSlot = $Connector->prepare('INSERT INTO `' . RP_TABLE_PREFIX . 'Attendance` ' . '( CharacterId, Class, UserId, RaidId, Status, Role, Comment ) ' . 'VALUES ( :CharId, :Class, :UserId, :RaidId, :Status, :Role, :Comment )');
                                    $UpdateSlot->bindValue(':CharId', $CharId, PDO::PARAM_INT);
                                    $UpdateSlot->bindValue(':Class', $ActiveClass, PDO::PARAM_STR);
                                    $UpdateSlot->bindValue(':UserId', $UserId, PDO::PARAM_INT);
                                    $UpdateSlot->bindValue(':Comment', $Comment, PDO::PARAM_STR);
                                } else {
                                    if (($Flags & PlayerFlagName) != 0) {
                                        // Random player. Set name.
                                        $UpdateSlot = $Connector->prepare('INSERT INTO `' . RP_TABLE_PREFIX . 'Attendance` ' . '( CharacterId, UserId, RaidId, Status, Class, Role, Comment ) ' . 'VALUES ( 0, 0, :RaidId, :Status, :Class, :Role, :Name )');
                                        $UpdateSlot->bindValue(':Name', $Name, PDO::PARAM_STR);
                                        $UpdateSlot->bindValue(':Class', '___', PDO::PARAM_STR);
                                    } else {
                                        $Out = Out::getInstance();
                                        $Out->pushError('Invalid user flags');
                                    }
                                }
                            }
                        } else {
                            // Update existing entries
                            if (($Flags & PlayerFlagComment) != 0 && ($Flags & PlayerFlagCharId) != 0) {
                                // Used when setting up an absent player
                                $UpdateSlot = $Connector->prepare('UPDATE `' . RP_TABLE_PREFIX . 'Attendance` SET ' . 'Status = :Status, CharacterId = :CharId, Class = :Class, Comment = :Comment, Role = :Role, LastUpdate = FROM_UNIXTIME(:TimestampNow) ' . 'WHERE RaidId = :RaidId AND LastUpdate = FROM_UNIXTIME(:LastUpdate) AND AttendanceId = :AttendanceId LIMIT 1');
                                $UpdateSlot->bindValue(':Comment', $Comment, PDO::PARAM_STR);
                                $UpdateSlot->bindValue(':CharId', $CharId, PDO::PARAM_INT);
                                $UpdateSlot->bindValue(':Class', $ActiveClass, PDO::PARAM_STR);
                            } else {
                                if (($Flags & PlayerFlagCharId) != 0) {
                                    // Used when changing a character
                                    $UpdateSlot = $Connector->prepare('UPDATE `' . RP_TABLE_PREFIX . 'Attendance` SET ' . 'Status = :Status, CharacterId = :CharId, Class = :Class, Role = :Role, LastUpdate = FROM_UNIXTIME(:TimestampNow) ' . 'WHERE RaidId = :RaidId AND LastUpdate = FROM_UNIXTIME(:LastUpdate) AND AttendanceId = :AttendanceId LIMIT 1');
                                    $UpdateSlot->bindValue(':CharId', $CharId, PDO::PARAM_INT);
                                    $UpdateSlot->bindValue(':Class', $ActiveClass, PDO::PARAM_STR);
                                } else {
                                    if (($Flags & PlayerFlagComment) != 0) {
                                        // Used when setting a player to absent
                                        $UpdateSlot = $Connector->prepare('UPDATE `' . RP_TABLE_PREFIX . 'Attendance` SET ' . 'Status = :Status, Comment = :Comment, Role = :Role, LastUpdate = FROM_UNIXTIME(:TimestampNow) ' . 'WHERE RaidId = :RaidId AND LastUpdate = FROM_UNIXTIME(:LastUpdate) AND AttendanceId = :AttendanceId LIMIT 1');
                                        $UpdateSlot->bindValue(':Comment', $Comment, PDO::PARAM_STR);
                                    } else {
                                        if (($Flags & PlayerFlagName) != 0) {
                                            // Used when changing the name of a random player
                                            $UpdateSlot = $Connector->prepare('UPDATE `' . RP_TABLE_PREFIX . 'Attendance` SET ' . 'Status = :Status, Role = :Role, Comment = :Name, LastUpdate = FROM_UNIXTIME(:TimestampNow) ' . 'WHERE RaidId = :RaidId AND LastUpdate = FROM_UNIXTIME(:LastUpdate) AND AttendanceId = :AttendanceId LIMIT 1');
                                            $UpdateSlot->bindValue(':Name', $Name, PDO::PARAM_STR);
                                        } else {
                                            // Existing player, update
                                            $UpdateSlot = $Connector->prepare('UPDATE `' . RP_TABLE_PREFIX . 'Attendance` SET ' . 'Status = :Status, Role = :Role, LastUpdate = FROM_UNIXTIME(:TimestampNow) ' . 'WHERE RaidId = :RaidId AND LastUpdate = FROM_UNIXTIME(:LastUpdate) AND AttendanceId = :AttendanceId LIMIT 1');
                                        }
                                    }
                                }
                            }
                            $UpdateSlot->bindValue(':AttendanceId', $Id, PDO::PARAM_INT);
                            $UpdateSlot->bindValue(':LastUpdate', $OldTimestamp, PDO::PARAM_INT);
                            $UpdateSlot->bindValue(':TimestampNow', time(), PDO::PARAM_INT);
                        }
                        $UpdateSlot->bindValue(':Status', $Status, PDO::PARAM_STR);
                        $UpdateSlot->bindValue(':RaidId', $aRequest['id'], PDO::PARAM_INT);
                        $UpdateSlot->bindValue(':Role', $Role['id'], PDO::PARAM_STR);
                        if (!$UpdateSlot->execute()) {
                            $Connector->rollBack();
                            return;
                            // ### return, error ###
                        }
                    }
                }
            }
            // Assure mode constraints
            if ($aRequest['mode'] == 'all') {
                // Mode 'all' means all players are either 'ok' or 'unavailable'
                $AttendenceQuery = $Connector->prepare('UPDATE `' . RP_TABLE_PREFIX . 'Attendance` SET Status = "ok" ' . 'WHERE RaidId = :RaidId AND Status = "available"');
                $AttendenceQuery->bindValue(':RaidId', $aRequest['id'], PDO::PARAM_INT);
                if (!$AttendenceQuery->execute()) {
                    $Connector->rollBack();
                    return;
                    // ### return, error ###
                }
            } else {
                if ($aRequest['mode'] != 'overbook') {
                    // Assure there not more 'ok' players than allowed by slot size
                    $SlotSizes = array_combine($aRequest['slotRoles'], $aRequest['slotCount']);
                    foreach ($aRequest['slotRoles'] as $RoleId) {
                        if ($SlotSizes[$RoleId] > 0) {
                            $AttendenceQuery = $Connector->prepare('SELECT AttendanceId ' . 'FROM `' . RP_TABLE_PREFIX . 'Attendance` ' . 'WHERE RaidId = :RaidId AND Status = "ok" AND Role = :RoleId ' . 'ORDER BY AttendanceId DESC LIMIT :MaxCount');
                            $AttendenceQuery->bindValue(':RaidId', $aRequest['id'], PDO::PARAM_INT);
                            $AttendenceQuery->bindValue(':RoleId', $RoleId, PDO::PARAM_STR);
                            $AttendenceQuery->bindValue(':MaxCount', $SlotSizes[$RoleId], PDO::PARAM_INT);
                            $LastAttend = $AttendenceQuery->fetchFirst();
                            if ($AttendenceQuery->getAffectedRows() == $SlotSizes[$RoleId]) {
                                // Fix the overhead
                                $FixQuery = $Connector->prepare('UPDATE `' . RP_TABLE_PREFIX . 'Attendance` SET Status = "available" ' . 'WHERE RaidId = :RaidId AND Status = "ok" AND Role = :RoleId ' . 'AND AttendanceId > :FirstId');
                                $FixQuery->bindValue(':RaidId', $aRequest['id'], PDO::PARAM_INT);
                                $FixQuery->bindValue(':RoleId', $RoleId, PDO::PARAM_STR);
                                $FixQuery->bindValue(':FirstId', $LastAttend['AttendanceId'], PDO::PARAM_INT);
                                if (!$FixQuery->execute()) {
                                    $Connector->rollBack();
                                    return;
                                    // ### return, error ###
                                }
                            }
                        }
                    }
                }
            }
        } while (!$Connector->commit());
        // Call plugins
        $RaidId = intval($aRequest['id']);
        PluginRegistry::ForEachPlugin(function ($PluginInstance) use($RaidId) {
            $PluginInstance->onRaidModify($RaidId);
        });
        // reload detailed view
        msgRaidDetail($aRequest);
    } else {
        $Out = Out::getInstance();
        $Out->pushError(L('AccessDenied'));
    }
}