public function executeAction($parameters)
 {
     $now = $this->_websoccer->getNowAsTimestamp();
     $user = $this->_websoccer->getUser();
     $teamId = $user->getClubId($this->_websoccer, $this->_db);
     if ($teamId < 1) {
         throw new Exception($this->_i18n->getMessage("feature_requires_team"));
     }
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $teamId);
     // check if duration is in range
     $min = $this->_websoccer->getConfig("trainingcamp_min_days");
     $max = $this->_websoccer->getConfig("trainingcamp_max_days");
     if ($parameters["days"] < $min || $parameters["days"] > $max) {
         throw new Exception(sprintf($this->_i18n->getMessage("trainingcamp_booking_err_invaliddays"), $min, $max));
     }
     // check if date is in future
     $startDateObj = DateTime::createFromFormat($this->_websoccer->getConfig("date_format") . " H:i", $parameters["start_date"] . " 00:00");
     $startDateTimestamp = $startDateObj->getTimestamp();
     $endDateTimestamp = $startDateTimestamp + 3600 * 24 * $parameters["days"];
     if ($startDateTimestamp <= $now) {
         throw new Exception($this->_i18n->getMessage("trainingcamp_booking_err_dateinpast"));
     }
     // check if too far in future
     $maxDate = $now + $this->_websoccer->getConfig("trainingcamp_booking_max_days_in_future") * 3600 * 24;
     if ($startDateTimestamp > $maxDate) {
         throw new Exception($this->_i18n->getMessage("trainingcamp_booking_err_datetoofar", $this->_websoccer->getConfig("trainingcamp_booking_max_days_in_future")));
     }
     // get camp details
     $camp = TrainingcampsDataService::getCampById($this->_websoccer, $this->_db, $parameters["id"]);
     if (!$camp) {
         throw new Exception("Illegal ID");
     }
     // check if user still has an open training camp
     $existingBookings = TrainingcampsDataService::getCampBookingsByTeam($this->_websoccer, $this->_db, $teamId);
     if (count($existingBookings)) {
         throw new Exception($this->_i18n->getMessage("trainingcamp_booking_err_existingbookings"));
     }
     // check if team can afford it.
     $playersOfTeam = PlayersDataService::getPlayersOfTeamById($this->_websoccer, $this->_db, $teamId);
     $totalCosts = $camp["costs"] * $parameters["days"] * count($playersOfTeam);
     if ($totalCosts >= $team["team_budget"]) {
         throw new Exception($this->_i18n->getMessage("trainingcamp_booking_err_tooexpensive"));
     }
     // check if there are matches within the time frame
     $matches = MatchesDataService::getMatchesByTeamAndTimeframe($this->_websoccer, $this->_db, $teamId, $startDateTimestamp, $endDateTimestamp);
     if (count($matches)) {
         throw new Exception($this->_i18n->getMessage("trainingcamp_booking_err_matcheswithintimeframe"));
     }
     // debit amount
     BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $teamId, $totalCosts, "trainingcamp_booking_costs_subject", $camp["name"]);
     // create camp booking
     $columns["verein_id"] = $teamId;
     $columns["lager_id"] = $camp["id"];
     $columns["datum_start"] = $startDateTimestamp;
     $columns["datum_ende"] = $endDateTimestamp;
     $this->_db->queryInsert($columns, $this->_websoccer->getConfig("db_prefix") . "_trainingslager_belegung");
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("trainingcamp_booking_success"), ""));
     return "trainingcamp";
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     $user = $this->_websoccer->getUser();
     // check if feature is enabled
     $exchangeRate = (int) $this->_websoccer->getConfig("premium_exchangerate_gamecurrency");
     if ($exchangeRate <= 0) {
         throw new Exception("featue is disabled!");
     }
     // check if user has a club.
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     if (!$clubId) {
         throw new Exception($this->_i18n->getMessage("feature_requires_team"));
     }
     // check if balance is enough
     $amount = $parameters["amount"];
     $balance = $user->premiumBalance;
     if ($balance < $amount) {
         throw new Exception($this->_i18n->getMessage("premium-exchange_err_balancenotenough"));
     }
     // validation only: redirect to confirmation page
     if ($parameters["validateonly"]) {
         return "premium-exchange-confirm";
     }
     // credit amount on team account
     BankAccountDataService::creditAmount($this->_websoccer, $this->_db, $clubId, $amount * $exchangeRate, "premium-exchange_team_subject", $user->username);
     // debit premium amount
     PremiumDataService::debitAmount($this->_websoccer, $this->_db, $user->id, $amount, "exchange-premium");
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("premium-exchange_success"), ""));
     return "premiumaccount";
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     // check if feature is enabled
     if (!$this->_websoccer->getConfig("enable_player_resignation")) {
         return;
     }
     $user = $this->_websoccer->getUser();
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     // check if it is own player
     $player = PlayersDataService::getPlayerById($this->_websoccer, $this->_db, $parameters["id"]);
     if ($clubId != $player["team_id"]) {
         throw new Exception("nice try");
     }
     // check violation of minimum team size
     $teamSize = $this->getTeamSize($clubId);
     if ($teamSize <= $this->_websoccer->getConfig("transfermarket_min_teamsize")) {
         throw new Exception($this->_i18n->getMessage("sell_player_teamsize_too_small", $teamSize));
     }
     // check and withdraw compensation
     if ($this->_websoccer->getConfig("player_resignation_compensation_matches") > 0) {
         $compensation = $this->_websoccer->getConfig("player_resignation_compensation_matches") * $player["player_contract_salary"];
         $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
         if ($team["team_budget"] <= $compensation) {
             throw new Exception($this->_i18n->getMessage("fireplayer_tooexpensive"));
         }
         BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $clubId, $compensation, "fireplayer_compensation_subject", $player["player_firstname"] . " " . $player["player_lastname"]);
     }
     $this->updatePlayer($player["player_id"]);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("fireplayer_success"), ""));
     return null;
 }
 public function executeAction($parameters)
 {
     // check if feature is enabled
     if (!$this->_websoccer->getConfig("lending_enabled")) {
         return NULL;
     }
     $user = $this->_websoccer->getUser();
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     // check if user has team
     if ($clubId == null) {
         throw new Exception($this->_i18n->getMessage("feature_requires_team"));
     }
     // check if it is already own player
     $player = PlayersDataService::getPlayerById($this->_websoccer, $this->_db, $parameters["id"]);
     if ($clubId == $player["team_id"]) {
         throw new Exception($this->_i18n->getMessage("lending_hire_err_ownplayer"));
     }
     // check if player is borrowed by any user
     if ($player["lending_owner_id"] > 0) {
         throw new Exception($this->_i18n->getMessage("lending_hire_err_borrowed_player"));
     }
     // check if player is offered for lending
     if ($player["lending_fee"] == 0) {
         throw new Exception($this->_i18n->getMessage("lending_hire_err_notoffered"));
     }
     // check if player is on transfermarket
     if ($player["player_transfermarket"] > 0) {
         throw new Exception($this->_i18n->getMessage("lending_err_on_transfermarket"));
     }
     // check min and max duration
     if ($parameters["matches"] < $this->_websoccer->getConfig("lending_matches_min") || $parameters["matches"] > $this->_websoccer->getConfig("lending_matches_max")) {
         throw new Exception(sprintf($this->_i18n->getMessage("lending_hire_err_illegalduration"), $this->_websoccer->getConfig("lending_matches_min"), $this->_websoccer->getConfig("lending_matches_max")));
     }
     // check player's contract length
     if ($parameters["matches"] >= $player["player_contract_matches"]) {
         throw new Exception($this->_i18n->getMessage("lending_hire_err_contractendingtoosoon", $player["player_contract_matches"]));
     }
     // check if team can pay fee and salary
     $fee = $parameters["matches"] * $player["lending_fee"];
     // team should have the money for at least 5 matches to pay him
     $minBudget = $fee + 5 * $player["player_contract_salary"];
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
     if ($team["team_budget"] < $minBudget) {
         throw new Exception($this->_i18n->getMessage("lending_hire_err_budget_too_low"));
     }
     // deduct and credit fee
     BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $clubId, $fee, "lending_fee_subject", $player["team_name"]);
     BankAccountDataService::creditAmount($this->_websoccer, $this->_db, $player["team_id"], $fee, "lending_fee_subject", $team["team_name"]);
     $this->updatePlayer($player["player_id"], $player["team_id"], $clubId, $parameters["matches"]);
     // create notification for owner
     $playerName = strlen($player["player_pseudonym"]) ? $player["player_pseudonym"] : $player["player_firstname"] . " " . $player["player_lastname"];
     if ($player["team_user_id"]) {
         NotificationsDataService::createNotification($this->_websoccer, $this->_db, $player["team_user_id"], "lending_notification_lent", array("player" => $playerName, "matches" => $parameters["matches"], "newteam" => $team["team_name"]), "lending_lent", "player", "id=" . $player["player_id"]);
     }
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("lending_hire_success"), ""));
     return "myteam";
 }
 public function executeAction($parameters)
 {
     // check if feature is enabled
     if (!$this->_websoccer->getConfig("youth_enabled") && $this->_websoccer->getConfig("youth_scouting_enabled")) {
         return NULL;
     }
     $user = $this->_websoccer->getUser();
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     // check if user has a club
     if ($clubId < 1) {
         throw new Exception($this->_i18n->getMessage("error_action_required_team"));
     }
     // check if break is violated
     $lastExecutionTimestamp = YouthPlayersDataService::getLastScoutingExecutionTime($this->_websoccer, $this->_db, $this->_websoccer->getUser()->getClubId($this->_websoccer, $this->_db));
     $nextPossibleExecutionTimestamp = $lastExecutionTimestamp + $this->_websoccer->getConfig("youth_scouting_break_hours") * 3600;
     $now = $this->_websoccer->getNowAsTimestamp();
     if ($now < $nextPossibleExecutionTimestamp) {
         throw new Exception($this->_i18n->getMessage("youthteam_scouting_err_breakviolation", $this->_websoccer->getFormattedDatetime($nextPossibleExecutionTimestamp)));
     }
     // check if valid country (if name files exists)
     $namesFolder = NAMES_DIRECTORY . "/" . $parameters["country"];
     if (!file_exists($namesFolder . "/firstnames.txt") || !file_exists($namesFolder . "/lastnames.txt")) {
         throw new Exception($this->_i18n->getMessage("youthteam_scouting_err_invalidcountry"));
     }
     // check if valid scout
     $scout = YouthPlayersDataService::getScoutById($this->_websoccer, $this->_db, $this->_i18n, $parameters["scoutid"]);
     // check if team can afford it.
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
     if ($team["team_budget"] <= $scout["fee"]) {
         throw new Exception($this->_i18n->getMessage("youthteam_scouting_err_notenoughbudget"));
     }
     // deduct fee
     BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $clubId, $scout["fee"], "youthteam_scouting_fee_subject", $scout["name"]);
     // has scout found someone?
     $found = TRUE;
     $succesProbability = (int) $this->_websoccer->getConfig("youth_scouting_success_probability");
     if ($this->_websoccer->getConfig("youth_scouting_success_probability") < 100) {
         $found = SimulationHelper::selectItemFromProbabilities(array(TRUE => $succesProbability, FALSE => 100 - $succesProbability));
     }
     // he found someone, so create youth player
     if ($found) {
         $this->createYouthPlayer($clubId, $scout, $parameters["country"]);
         // create failure message
     } else {
         $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_WARNING, $this->_i18n->getMessage("youthteam_scouting_failure"), ""));
     }
     // update last execution time
     $this->_db->queryUpdate(array("scouting_last_execution" => $now), $this->_websoccer->getConfig("db_prefix") . "_verein", "id = %d", $clubId);
     return $found ? "youth-team" : "youth-scouting";
 }
 public function getTemplateParameters()
 {
     $teamId = $this->_websoccer->getUser()->getClubId($this->_websoccer, $this->_db);
     if ($teamId < 1) {
         throw new Exception($this->_i18n->getMessage("feature_requires_team"));
     }
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $teamId);
     $count = BankAccountDataService::countAccountStatementsOfTeam($this->_websoccer, $this->_db, $teamId);
     $eps = $this->_websoccer->getConfig("entries_per_page");
     $paginator = new Paginator($count, $eps, $this->_websoccer);
     if ($count > 0) {
         $statements = BankAccountDataService::getAccountStatementsOfTeam($this->_websoccer, $this->_db, $teamId, $paginator->getFirstIndex(), $eps);
     } else {
         $statements = array();
     }
     return array("budget" => $team["team_budget"], "statements" => $statements, "paginator" => $paginator);
 }
 public function executeAction($parameters)
 {
     // check if feature is enabled
     if (!$this->_websoccer->getConfig("youth_enabled") || !$this->_websoccer->getConfig("youth_matchrequests_enabled")) {
         return NULL;
     }
     $user = $this->_websoccer->getUser();
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     // get request info
     $fromTable = $this->_websoccer->getConfig("db_prefix") . "_youthmatch_request";
     $result = $this->_db->querySelect("*", $fromTable, "id = %d", $parameters["id"]);
     $request = $result->fetch_array();
     $result->free();
     if (!$request) {
         throw new Exception($this->_i18n->getMessage("youthteam_matchrequest_cancel_err_notfound"));
     }
     // check if own request
     if ($clubId == $request["team_id"]) {
         throw new Exception($this->_i18n->getMessage("youthteam_matchrequest_accept_err_ownrequest"));
     }
     // check if team has enough youth players
     if (YouthPlayersDataService::countYouthPlayersOfTeam($this->_websoccer, $this->_db, $clubId) < 11) {
         throw new Exception($this->_i18n->getMessage("youthteam_matchrequest_create_err_notenoughplayers"));
     }
     // check maximum number of matches on same day
     $maxMatchesPerDay = $this->_websoccer->getConfig("youth_match_maxperday");
     if (YouthMatchesDataService::countMatchesOfTeamOnSameDay($this->_websoccer, $this->_db, $clubId, $request["matchdate"]) >= $maxMatchesPerDay) {
         throw new Exception($this->_i18n->getMessage("youthteam_matchrequest_err_maxperday_violated", $maxMatchesPerDay));
     }
     $homeTeam = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $request["team_id"]);
     $guestTeam = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
     // deduct/credit transfer reward
     if ($request["reward"]) {
         BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $request["team_id"], $request["reward"], "youthteam_matchrequest_reward_subject", $guestTeam["team_name"]);
         BankAccountDataService::creditAmount($this->_websoccer, $this->_db, $clubId, $request["reward"], "youthteam_matchrequest_reward_subject", $homeTeam["team_name"]);
     }
     // create match
     $this->_db->queryInsert(array("matchdate" => $request["matchdate"], "home_team_id" => $request["team_id"], "guest_team_id" => $clubId), $this->_websoccer->getConfig("db_prefix") . "_youthmatch");
     // delete match request
     $this->_db->queryDelete($fromTable, "id = %d", $parameters["id"]);
     // send notification to user
     NotificationsDataService::createNotification($this->_websoccer, $this->_db, $homeTeam["user_id"], "youthteam_matchrequest_accept_notification", array("team" => $guestTeam["team_name"], "date" => $this->_websoccer->getFormattedDatetime($request["matchdate"])), "youthmatch_accept", "youth-matches", null, $request["team_id"]);
     // create success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("youthteam_matchrequest_accept_success"), $this->_i18n->getMessage("youthteam_matchrequest_accept_success_details")));
     return "youth-matches";
 }
 /**
  * pay salary ans triger player updates.
  * 
  * @param SimulationMatch $match
  * @param SimulationTeam $team
  */
 private function _updateTeam(SimulationMatch $match, SimulationTeam $team)
 {
     // debit players salary
     $salary = YouthPlayersDataService::computeSalarySumOfYouthPlayersOfTeam($this->_websoccer, $this->_db, $team->id);
     if ($salary) {
         BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $team->id, $salary, 'youthteam_salarypayment_subject', 'match_salarypayment_sender');
     }
     // update players who played
     if (is_array($team->positionsAndPlayers)) {
         foreach ($team->positionsAndPlayers as $position => $players) {
             foreach ($players as $player) {
                 $this->_updatePlayer($match, $player, TRUE);
             }
         }
     }
     if (is_array($team->removedPlayers)) {
         foreach ($team->removedPlayers as $player) {
             $this->_updatePlayer($match, $player, FALSE);
         }
     }
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     $user = $this->_websoccer->getUser();
     $teamId = $user->getClubId($this->_websoccer, $this->_db);
     if ($teamId < 1) {
         throw new Exception($this->_i18n->getMessage("feature_requires_team"));
     }
     if (TrainingDataService::countRemainingTrainingUnits($this->_websoccer, $this->_db, $teamId)) {
         throw new Exception($this->_i18n->getMessage("training_choose_trainer_err_existing_units"));
     }
     // trainer info
     $trainer = TrainingDataService::getTrainerById($this->_websoccer, $this->_db, $parameters["id"]);
     if (!isset($trainer["id"])) {
         throw new Exception("invalid ID");
     }
     // can team afford it?
     $numberOfUnits = (int) $parameters["units"];
     $totalCosts = $numberOfUnits * $trainer["salary"];
     $teamInfo = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $teamId);
     if ($teamInfo["team_budget"] <= $totalCosts) {
         throw new Exception($this->_i18n->getMessage("training_choose_trainer_err_too_expensive"));
     }
     // try to debit premium fee
     if ($trainer['premiumfee']) {
         PremiumDataService::debitAmount($this->_websoccer, $this->_db, $user->id, $trainer['premiumfee'], "choose-trainer");
     }
     // debit money
     BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $teamId, $totalCosts, "training_trainer_salary_subject", $trainer["name"]);
     // create new units
     $columns["team_id"] = $teamId;
     $columns["trainer_id"] = $trainer["id"];
     $fromTable = $this->_websoccer->getConfig("db_prefix") . "_training_unit";
     for ($unitNo = 1; $unitNo <= $numberOfUnits; $unitNo++) {
         $this->_db->queryInsert($columns, $fromTable);
     }
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("saved_message_title"), ""));
     // redirect to training overview
     return "training";
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     // check if feature is enabled
     if (!$this->_websoccer->getConfig("youth_enabled")) {
         return NULL;
     }
     $user = $this->_websoccer->getUser();
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     if ($clubId < 1) {
         throw new Exception($this->_i18n->getMessage("feature_requires_team"));
     }
     // check if it is already own player
     $player = YouthPlayersDataService::getYouthPlayerById($this->_websoccer, $this->_db, $this->_i18n, $parameters["id"]);
     if ($clubId == $player["team_id"]) {
         throw new Exception($this->_i18n->getMessage("youthteam_buy_err_ownplayer"));
     }
     // player must not be tranfered from one of user's other teams
     $result = $this->_db->querySelect("user_id", $this->_websoccer->getConfig("db_prefix") . "_verein", "id = %d", $player["team_id"]);
     $playerteam = $result->fetch_array();
     $result->free_result();
     if ($playerteam["user_id"] == $user->id) {
         throw new Exception($this->_i18n->getMessage("youthteam_buy_err_ownplayer_otherteam"));
     }
     // check if enough budget
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
     if ($team["team_budget"] <= $player["transfer_fee"]) {
         throw new Exception($this->_i18n->getMessage("youthteam_buy_err_notenoughbudget"));
     }
     // credit / debit amount
     $prevTeam = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $player["team_id"]);
     BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $clubId, $player["transfer_fee"], "youthteam_transferfee_subject", $prevTeam["team_name"]);
     BankAccountDataService::creditAmount($this->_websoccer, $this->_db, $player["team_id"], $player["transfer_fee"], "youthteam_transferfee_subject", $team["team_name"]);
     // update player
     $this->_db->queryUpdate(array("team_id" => $clubId, "transfer_fee" => 0), $this->_websoccer->getConfig("db_prefix") . "_youthplayer", "id = %d", $parameters["id"]);
     // create notification
     NotificationsDataService::createNotification($this->_websoccer, $this->_db, $prevTeam["user_id"], "youthteam_transfer_notification", array("player" => $player["firstname"] . " " . $player["lastname"], "newteam" => $team["team_name"]), "youth_transfer", "team", "id=" . $clubId);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("youthteam_buy_success"), ""));
     return "youth-team";
 }
 /**
  * Executes a transfer according to direct transfer offer. Deletes all offers for this player on success.
  * 
  * @param WebSoccer $websoccer application context.
  * @param DbConnection $db DB connection.
  * @param unknown $offerId id of direct transfer offer.
  */
 public static function executeTransferFromOffer(WebSoccer $websoccer, DbConnection $db, $offerId)
 {
     // offer data
     $result = $db->querySelect("*", $websoccer->getConfig("db_prefix") . "_transfer_offer", "id = %d", $offerId);
     $offer = $result->fetch_array();
     $result->free();
     if (!$offer) {
         return;
     }
     $currentTeam = TeamsDataService::getTeamSummaryById($websoccer, $db, $offer["receiver_club_id"]);
     $targetTeam = TeamsDataService::getTeamSummaryById($websoccer, $db, $offer["sender_club_id"]);
     // move player (and create transfer log)
     self::_transferPlayer($websoccer, $db, $offer["player_id"], $offer["sender_club_id"], $offer["sender_user_id"], $currentTeam["user_id"], $offer["receiver_club_id"], $offer["offer_amount"], $offer["offer_player1"], $offer["offer_player2"]);
     // credit amount
     BankAccountDataService::creditAmount($websoccer, $db, $offer["receiver_club_id"], $offer["offer_amount"], "directtransfer_subject", $targetTeam["team_name"]);
     // debit amount
     BankAccountDataService::debitAmount($websoccer, $db, $offer["sender_club_id"], $offer["offer_amount"], "directtransfer_subject", $currentTeam["team_name"]);
     // move exchange players
     if ($offer["offer_player1"]) {
         self::_transferPlayer($websoccer, $db, $offer["offer_player1"], $offer["receiver_club_id"], $currentTeam["user_id"], $targetTeam["user_id"], $offer["sender_club_id"], 0, $offer["player_id"]);
     }
     if ($offer["offer_player2"]) {
         self::_transferPlayer($websoccer, $db, $offer["offer_player2"], $offer["receiver_club_id"], $currentTeam["user_id"], $targetTeam["user_id"], $offer["sender_club_id"], 0, $offer["player_id"]);
     }
     // delete offer and other offers for this player
     $db->queryDelete($websoccer->getConfig("db_prefix") . "_transfer_offer", "player_id = %d", $offer["player_id"]);
     // get player name for notification
     $player = PlayersDataService::getPlayerById($websoccer, $db, $offer["player_id"]);
     if ($player["player_pseudonym"]) {
         $playerName = $player["player_pseudonym"];
     } else {
         $playerName = $player["player_firstname"] . " " . $player["player_lastname"];
     }
     // notify and award users
     NotificationsDataService::createNotification($websoccer, $db, $currentTeam["user_id"], "transferoffer_notification_executed", array("playername" => $playerName), NOTIFICATION_TYPE, "player", "id=" . $offer["player_id"], $currentTeam["team_id"]);
     NotificationsDataService::createNotification($websoccer, $db, $offer["sender_user_id"], "transferoffer_notification_executed", array("playername" => $playerName), NOTIFICATION_TYPE, "player", "id=" . $offer["player_id"], $targetTeam['team_id']);
     TransfermarketDataService::awardUserForTrades($websoccer, $db, $currentTeam["user_id"]);
     TransfermarketDataService::awardUserForTrades($websoccer, $db, $offer["sender_user_id"]);
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     $user = $this->_websoccer->getUser();
     $teamId = $user->getClubId($this->_websoccer, $this->_db);
     if ($teamId < 1) {
         return null;
     }
     // validate type parameter
     $type = $parameters["type"];
     if (!in_array($type, array("pitch", "videowall", "seatsquality", "vipquality"))) {
         throw new Exception("illegal parameter: type");
     }
     $stadium = StadiumsDataService::getStadiumByTeamId($this->_websoccer, $this->_db, $teamId);
     if (!$stadium) {
         return null;
     }
     $existingLevel = $stadium["level_" . $type];
     // upgradable?
     if ($existingLevel >= 5) {
         throw new Exception($this->_i18n->getMessage("stadium_upgrade_err_not_upgradable"));
     }
     // can user afford it?
     $costs = StadiumsDataService::computeUpgradeCosts($this->_websoccer, $type, $stadium);
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $teamId);
     if ($team["team_budget"] <= $costs) {
         throw new Exception($this->_i18n->getMessage("stadium_extend_err_too_expensive"));
     }
     // debit money
     BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $teamId, $costs, "stadium_upgrade_transaction_subject", $stadium["name"]);
     // update stadium
     $maintenanceDue = (int) $this->_websoccer->getConfig("stadium_maintenanceinterval_" . $type);
     $this->_db->queryUpdate(array("level_" . $type => $existingLevel + 1, "maintenance_" . $type => $maintenanceDue), $this->_websoccer->getConfig("db_prefix") . "_stadion", "id = %d", $stadium["stadium_id"]);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("stadium_upgrade_success"), $this->_i18n->getMessage("stadium_upgrade_success_details")));
     return "stadium";
 }
 /**
  * Pays configured cup round awards (such as per round or winner/second of final round)
  * and creates actual matches for next cup round, if available.
  * 
  * @param WebSoccer $websoccer application context.
  * @param DbConnection $db DB Connection-
  * @param int $winnerTeamId ID of winner team.
  * @param int $loserTeamId ID of loser team.
  * @param string $cupName matche's cup name.
  * @param string $cupRound matche's cup round name.
  */
 public static function createNextRoundMatchAndPayAwards(WebSoccer $websoccer, DbConnection $db, $winnerTeamId, $loserTeamId, $cupName, $cupRound)
 {
     // rounds and cup info
     $columns['C.id'] = 'cup_id';
     $columns['C.winner_award'] = 'cup_winner_award';
     $columns['C.second_award'] = 'cup_second_award';
     $columns['C.perround_award'] = 'cup_perround_award';
     $columns['R.id'] = 'round_id';
     $columns['R.finalround'] = 'is_finalround';
     $fromTable = $websoccer->getConfig('db_prefix') . '_cup_round AS R';
     $fromTable .= ' INNER JOIN ' . $websoccer->getConfig('db_prefix') . '_cup AS C ON C.id = R.cup_id';
     $result = $db->querySelect($columns, $fromTable, 'C.name = \'%s\' AND R.name = \'%s\'', array($cupName, $cupRound), 1);
     $round = $result->fetch_array();
     $result->free();
     // do nothing if no round is configured
     if (!$round) {
         return;
     }
     // credit per round award
     if ($round['cup_perround_award']) {
         BankAccountDataService::creditAmount($websoccer, $db, $winnerTeamId, $round['cup_perround_award'], 'cup_cuproundaward_perround_subject', $cupName);
         BankAccountDataService::creditAmount($websoccer, $db, $loserTeamId, $round['cup_perround_award'], 'cup_cuproundaward_perround_subject', $cupName);
     }
     $result = $db->querySelect('user_id', $websoccer->getConfig('db_prefix') . '_verein', 'id = %d', $winnerTeamId);
     $winnerclub = $result->fetch_array();
     $result->free();
     $result = $db->querySelect('user_id', $websoccer->getConfig('db_prefix') . '_verein', 'id = %d', $loserTeamId);
     $loserclub = $result->fetch_array();
     $result->free();
     // create achievement log
     $now = $websoccer->getNowAsTimestamp();
     if ($winnerclub['user_id']) {
         $db->queryInsert(array('user_id' => $winnerclub['user_id'], 'team_id' => $winnerTeamId, 'cup_round_id' => $round['round_id'], 'date_recorded' => $now), $websoccer->getConfig('db_prefix') . '_achievement');
     }
     if ($loserclub['user_id']) {
         $db->queryInsert(array('user_id' => $loserclub['user_id'], 'team_id' => $loserTeamId, 'cup_round_id' => $round['round_id'], 'date_recorded' => $now), $websoccer->getConfig('db_prefix') . '_achievement');
     }
     // was final round?
     if ($round['is_finalround']) {
         // credit awards
         if ($round['cup_winner_award']) {
             BankAccountDataService::creditAmount($websoccer, $db, $winnerTeamId, $round['cup_winner_award'], 'cup_cuproundaward_winner_subject', $cupName);
         }
         if ($round['cup_second_award']) {
             BankAccountDataService::creditAmount($websoccer, $db, $loserTeamId, $round['cup_second_award'], 'cup_cuproundaward_second_subject', $cupName);
         }
         // update 'winner flag' of cup
         $db->queryUpdate(array('winner_id' => $winnerTeamId), $websoccer->getConfig('db_prefix') . '_cup', 'id = %d', $round['cup_id']);
         // award badge
         if ($winnerclub['user_id']) {
             BadgesDataService::awardBadgeIfApplicable($websoccer, $db, $winnerclub['user_id'], 'cupwinner');
         }
         // create matches for next round
     } else {
         $columns = 'id,firstround_date,secondround_date,name';
         $fromTable = $websoccer->getConfig('db_prefix') . '_cup_round';
         // get next round for winner
         $result = $db->querySelect($columns, $fromTable, 'from_winners_round_id = %d', $round['round_id'], 1);
         $winnerRound = $result->fetch_array();
         $result->free();
         if (isset($winnerRound['id'])) {
             self::createMatchForTeamAndRound($websoccer, $db, $winnerTeamId, $winnerRound['id'], $winnerRound['firstround_date'], $winnerRound['secondround_date'], $cupName, $winnerRound['name']);
         }
         // get next round for loser
         $result = $db->querySelect($columns, $fromTable, 'from_loosers_round_id = %d', $round['round_id'], 1);
         $loserRound = $result->fetch_array();
         $result->free();
         if (isset($loserRound['id'])) {
             self::createMatchForTeamAndRound($websoccer, $db, $loserTeamId, $loserRound['id'], $loserRound['firstround_date'], $loserRound['secondround_date'], $cupName, $loserRound['name']);
         }
     }
 }
 /**
  * Computes and stores the audience, including crediting the sales revenue.
  * Considers following factors:
  * - Fan popularity
  * - Ticket prices (compared to league average prices, which are set by the admin)
  * - bonus if the match is attractive. It is attractive if it is a cup match or if teams are neighbors in the standings.
  * 
  * @param WebSoccer $websoccer request context.
  * @param DbConnection $db database connection.
  * @param SimulationMatch $match Simulation match for that the audience shall be computed.
  */
 public static function computeAndSaveAudience(WebSoccer $websoccer, DbConnection $db, SimulationMatch $match)
 {
     // get stadium, user and team info
     $homeInfo = self::getHomeInfo($websoccer, $db, $match->homeTeam->id);
     if (!$homeInfo) {
         return;
     }
     // is match in particular attractive?
     $isAttractiveMatch = FALSE;
     if ($match->type == 'Pokalspiel') {
         $isAttractiveMatch = TRUE;
     } else {
         if ($match->type == 'Ligaspiel') {
             // consider difference between points
             $tcolumns = 'sa_punkte';
             $fromTable = $websoccer->getConfig('db_prefix') . '_verein';
             $whereCondition = 'id = %d';
             $result = $db->querySelect($tcolumns, $fromTable, $whereCondition, $match->homeTeam->id);
             $home = $result->fetch_array();
             $result->free();
             $result = $db->querySelect($tcolumns, $fromTable, $whereCondition, $match->guestTeam->id);
             $guest = $result->fetch_array();
             $result->free();
             if (abs($home['sa_punkte'] - $guest['sa_punkte']) <= 9) {
                 $isAttractiveMatch = TRUE;
             }
         }
     }
     // consider stadium extras
     $maintenanceInfluence = $homeInfo['level_videowall'] * $websoccer->getConfig('stadium_videowall_effect');
     $maintenanceInfluenceSeats = (5 - $homeInfo['level_seatsquality']) * $websoccer->getConfig('stadium_seatsquality_effect');
     $maintenanceInfluenceVip = (5 - $homeInfo['level_vipquality']) * $websoccer->getConfig('stadium_vipquality_effect');
     // compute sold tickets
     $rateStands = self::computeRate($homeInfo['avg_price_stands'], $homeInfo['avg_sales_stands'], $homeInfo['price_stands'], $homeInfo['popularity'], $isAttractiveMatch, $maintenanceInfluence);
     $rateSeats = self::computeRate($homeInfo['avg_price_seats'], $homeInfo['avg_sales_seats'], $homeInfo['price_seats'], $homeInfo['popularity'], $isAttractiveMatch, $maintenanceInfluence - $maintenanceInfluenceSeats);
     $rateStandsGrand = self::computeRate($homeInfo['avg_price_stands'] * 1.2, $homeInfo['avg_sales_stands_grand'], $homeInfo['price_stands_grand'], $homeInfo['popularity'], $isAttractiveMatch, $maintenanceInfluence);
     $rateSeatsGrand = self::computeRate($homeInfo['avg_price_seats'] * 1.2, $homeInfo['avg_sales_seats_grand'], $homeInfo['price_seats_grand'], $homeInfo['popularity'], $isAttractiveMatch, $maintenanceInfluence - $maintenanceInfluenceSeats);
     $rateVip = self::computeRate($homeInfo['avg_price_vip'], $homeInfo['avg_sales_vip'], $homeInfo['price_vip'], $homeInfo['popularity'], $isAttractiveMatch, $maintenanceInfluence - $maintenanceInfluenceVip);
     // call plug-ins
     $event = new TicketsComputedEvent($websoccer, $db, I18n::getInstance($websoccer->getConfig('supported_languages')), $match, $homeInfo['stadium_id'], $rateStands, $rateSeats, $rateStandsGrand, $rateSeatsGrand, $rateVip);
     PluginMediator::dispatchEvent($event);
     // is sold out?
     if ($rateStands == 1 && $rateSeats == 1 && $rateStandsGrand == 1 && $rateSeatsGrand == 1 && $rateVip == 1) {
         $match->isSoldOut = TRUE;
     }
     $tickets_stands = min(1, max(0, $rateStands)) * $homeInfo['places_stands'];
     $tickets_seats = min(1, max(0, $rateSeats)) * $homeInfo['places_seats'];
     $tickets_stands_grand = min(1, max(0, $rateStandsGrand)) * $homeInfo['places_stands_grand'];
     $tickets_seats_grand = min(1, max(0, $rateSeatsGrand)) * $homeInfo['places_seats_grand'];
     $tickets_vip = min(1, max(0, $rateVip)) * $homeInfo['places_vip'];
     // update team statistic
     $columns['last_steh'] = $tickets_stands;
     $columns['last_sitz'] = $tickets_seats;
     $columns['last_haupt_steh'] = $tickets_stands_grand;
     $columns['last_haupt_sitz'] = $tickets_seats_grand;
     $columns['last_vip'] = $tickets_vip;
     $fromTable = $websoccer->getConfig('db_prefix') . '_verein';
     $whereCondition = 'id = %d';
     $db->queryUpdate($columns, $fromTable, $whereCondition, $match->homeTeam->id);
     // update match field
     $mcolumns['zuschauer'] = $tickets_stands + $tickets_seats + $tickets_stands_grand + $tickets_seats_grand + $tickets_vip;
     $fromTable = $websoccer->getConfig('db_prefix') . '_spiel';
     $db->queryUpdate($mcolumns, $fromTable, $whereCondition, $match->id);
     // compute and credit income
     $revenue = $tickets_stands * $homeInfo['price_stands'];
     $revenue += $tickets_seats * $homeInfo['price_seats'];
     $revenue += $tickets_stands_grand * $homeInfo['price_stands_grand'];
     $revenue += $tickets_seats_grand * $homeInfo['price_seats_grand'];
     $revenue += $tickets_vip * $homeInfo['price_vip'];
     BankAccountDataService::creditAmount($websoccer, $db, $match->homeTeam->id, $revenue, 'match_ticketrevenue_subject', 'match_ticketrevenue_sender');
     self::weakenPlayersDueToGrassQuality($websoccer, $homeInfo, $match);
     self::updateMaintenanceStatus($websoccer, $db, $homeInfo);
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     $user = $this->_websoccer->getUser();
     $teamId = $user->getClubId($this->_websoccer, $this->_db);
     if ($teamId < 1) {
         return null;
     }
     // any number entered?
     if (!$parameters["side_standing"] && !$parameters["side_seats"] && !$parameters["grand_standing"] && !$parameters["grand_seats"] && !$parameters["vip"]) {
         return null;
     }
     $stadium = StadiumsDataService::getStadiumByTeamId($this->_websoccer, $this->_db, $teamId);
     if (!$stadium) {
         return null;
     }
     // max limit exceeded?
     $seatsSide = $stadium["places_stands"] + $stadium["places_seats"] + $parameters["side_standing"] + $parameters["side_seats"];
     if ($seatsSide > $this->_websoccer->getConfig("stadium_max_side")) {
         throw new Exception($this->_i18n->getMessage("stadium_extend_err_exceed_max_side", $this->_websoccer->getConfig("stadium_max_side")));
     }
     $seatsGrand = $stadium["places_stands_grand"] + $stadium["places_seats_grand"] + $parameters["grand_standing"] + $parameters["grand_seats"];
     if ($seatsGrand > $this->_websoccer->getConfig("stadium_max_grand")) {
         throw new Exception($this->_i18n->getMessage("stadium_extend_err_exceed_max_grand", $this->_websoccer->getConfig("stadium_max_grand")));
     }
     $seatsVip = $stadium["places_vip"] + $parameters["vip"];
     if ($seatsVip > $this->_websoccer->getConfig("stadium_max_vip")) {
         throw new Exception($this->_i18n->getMessage("stadium_extend_err_exceed_max_vip", $this->_websoccer->getConfig("stadium_max_vip")));
     }
     // is construction already on-going?
     if (StadiumsDataService::getCurrentConstructionOrderOfTeam($this->_websoccer, $this->_db, $teamId) != NULL) {
         throw new Exception($this->_i18n->getMessage("stadium_extend_err_constructionongoing"));
     }
     if (isset($parameters["validate-only"]) && $parameters["validate-only"]) {
         return "stadium-extend-confirm";
     }
     // builder got selected? Illegal builder ID can only happen due to a bug or user input manipulation.
     $builderId = $this->_websoccer->getRequestParameter("offerid");
     $offers = StadiumsDataService::getBuilderOffersForExtension($this->_websoccer, $this->_db, $teamId, (int) $this->_websoccer->getRequestParameter("side_standing"), (int) $this->_websoccer->getRequestParameter("side_seats"), (int) $this->_websoccer->getRequestParameter("grand_standing"), (int) $this->_websoccer->getRequestParameter("grand_seats"), (int) $this->_websoccer->getRequestParameter("vip"));
     if ($builderId == NULL || !isset($offers[$builderId])) {
         throw new Exception("Illegal offer ID.");
     }
     // can user afford it?
     $offer = $offers[$builderId];
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $teamId);
     $totalCosts = $offer["totalCosts"];
     if ($team["team_budget"] <= $totalCosts) {
         throw new Exception($this->_i18n->getMessage("stadium_extend_err_too_expensive"));
     }
     // try to debit premium fee
     if ($offer["builder_premiumfee"]) {
         PremiumDataService::debitAmount($this->_websoccer, $this->_db, $user->id, $offer["builder_premiumfee"], "extend-stadium");
     }
     // debit money
     BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $teamId, $totalCosts, "stadium_extend_transaction_subject", $offer["builder_name"]);
     // create construction order
     $this->_db->queryInsert(array("team_id" => $teamId, "builder_id" => $builderId, "started" => $this->_websoccer->getNowAsTimestamp(), "deadline" => $offer["deadline"], "p_steh" => $parameters["side_standing"] ? $parameters["side_standing"] : 0, "p_sitz" => $parameters["side_seats"] ? $parameters["side_seats"] : 0, "p_haupt_steh" => $parameters["grand_standing"] ? $parameters["grand_standing"] : 0, "p_haupt_sitz" => $parameters["grand_seats"] ? $parameters["grand_seats"] : 0, "p_vip" => $parameters["vip"] ? $parameters["vip"] : 0), $this->_websoccer->getConfig("db_prefix") . "_stadium_construction");
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("stadium_extend_success"), ""));
     // create action log manually here, ceause of this great "validate-only" idea...
     ActionLogDataService::createOrUpdateActionLog($this->_websoccer, $this->_db, $user->id, "extend-stadium");
     $seats = $parameters["side_standing"] + $parameters["side_seats"] + $parameters["grand_standing"] + $parameters["grand_seats"] + $parameters["vip"];
     BadgesDataService::awardBadgeIfApplicable($this->_websoccer, $this->_db, $user->id, 'stadium_construction_by_x', $seats);
     return "stadium";
 }
             $userres = $db->querySelect('fanbeliebtheit', $conf['db_prefix'] . '_user', 'id = %d', $team['user_id']);
             $manager = $userres->fetch_array();
             if ($manager) {
                 $popularity = max(1, $manager['fanbeliebtheit'] - $_POST['target_missed_popularityreduction']);
                 $db->queryUpdate(array('fanbeliebtheit' => $popularity), $conf['db_prefix'] . '_user', 'id = %d', $team['user_id']);
             }
             $userres->free();
         }
         // debit penalty
         if ($_POST['target_missed_penalty'] > 0) {
             BankAccountDataService::debitAmount($website, $db, $team['id'], $_POST['target_missed_penalty'], 'seasontarget_failed_penalty_subject', $website->getConfig('projectname'));
         }
         // pay reward for accomplishing target
     } else {
         if ($team['min_target_rank'] > 0 && $team['min_target_rank'] >= $rank && $_POST['target_accomplished_reward'] > 0) {
             BankAccountDataService::creditAmount($website, $db, $team['id'], $_POST['target_accomplished_reward'], 'seasontarget_accomplished_reward_subject', $website->getConfig('projectname'));
         }
     }
 }
 // increase age of youth players
 $youthresult = $db->querySelect('id,age', $conf['db_prefix'] . '_youthplayer', 'team_id = %d', $team['id']);
 while ($youthplayer = $youthresult->fetch_array()) {
     $playerage = $youthplayer['age'] + 1;
     // delete youth player
     if ($maxYouthAge > 0 && $maxYouthAge <= $playerage) {
         $db->queryDelete($conf['db_prefix'] . '_youthplayer', 'id = %d', $youthplayer['id']);
         // update youth player
     } else {
         $db->queryUpdate(array('age' => $playerage), $conf['db_prefix'] . '_youthplayer', 'id = %d', $youthplayer['id']);
     }
 }
 private function transferPlayer(WebSoccer $websoccer, DbConnection $db, $player, $bid)
 {
     $playerName = strlen($player['pseudonym']) ? $player['pseudonym'] : $player['first_name'] . ' ' . $player['last_name'];
     // transfer without fee
     if ($player['team_id'] < 1) {
         // debit hand money
         if ($bid['hand_money'] > 0) {
             BankAccountDataService::debitAmount($websoccer, $db, $bid['team_id'], $bid['hand_money'], 'transfer_transaction_subject_handmoney', $playerName);
         }
         // debit / credit fee
     } else {
         BankAccountDataService::debitAmount($websoccer, $db, $bid['team_id'], $bid['amount'], 'transfer_transaction_subject_fee', $player['team_name']);
         BankAccountDataService::creditAmount($websoccer, $db, $player['team_id'], $bid['amount'], 'transfer_transaction_subject_fee', $bid['team_name']);
     }
     $fromTable = $websoccer->getConfig('db_prefix') . '_spieler';
     // move and update player
     $columns['transfermarkt'] = 0;
     $columns['transfer_start'] = 0;
     $columns['transfer_ende'] = 0;
     $columns['verein_id'] = $bid['team_id'];
     $columns['vertrag_spiele'] = $bid['contract_matches'];
     $columns['vertrag_gehalt'] = $bid['contract_salary'];
     $columns['vertrag_torpraemie'] = $bid['contract_goalbonus'];
     $whereCondition = 'id = %d';
     $db->queryUpdate($columns, $fromTable, $whereCondition, $player['player_id']);
     // create transfer log
     $logcolumns['spieler_id'] = $player['player_id'];
     $logcolumns['seller_user_id'] = $player['team_user_id'];
     $logcolumns['seller_club_id'] = $player['team_id'];
     $logcolumns['buyer_user_id'] = $bid['user_id'];
     $logcolumns['buyer_club_id'] = $bid['team_id'];
     $logcolumns['datum'] = $websoccer->getNowAsTimestamp();
     $logcolumns['directtransfer_amount'] = $bid['amount'];
     $logTable = $websoccer->getConfig('db_prefix') . '_transfer';
     $db->queryInsert($logcolumns, $logTable);
     // notify user
     NotificationsDataService::createNotification($websoccer, $db, $bid['user_id'], 'transfer_bid_notification_transfered', array('player' => $playerName), 'transfermarket', 'player', 'id=' . $player['player_id']);
     // delete old bids
     $db->queryDelete($websoccer->getConfig('db_prefix') . '_transfer_angebot', 'spieler_id = %d', $player['player_id']);
     // award badges
     self::awardUserForTrades($websoccer, $db, $bid['user_id']);
     if ($player['team_user_id']) {
         self::awardUserForTrades($websoccer, $db, $player['team_user_id']);
     }
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     $buildingId = $parameters['id'];
     $user = $this->_websoccer->getUser();
     $teamId = $user->getClubId($this->_websoccer, $this->_db);
     if (!$teamId) {
         throw new Exception($this->_i18n->getMessage("feature_requires_team"));
     }
     $dbPrefix = $this->_websoccer->getConfig('db_prefix');
     $result = $this->_db->querySelect('*', $dbPrefix . '_stadiumbuilding', 'id = %d', $buildingId);
     $building = $result->fetch_array();
     $result->free();
     if (!$building) {
         // no i18n required since this should actually not happen if used properly.
         throw new Exception('illegal building.');
     }
     // check budget
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $teamId);
     if ($team['team_budget'] <= $building['costs']) {
         throw new Exception($this->_i18n->getMessage('stadiumenvironment_build_err_too_expensive'));
     }
     // check if already exists in team
     $result = $this->_db->querySelect('*', $dbPrefix . '_buildings_of_team', 'team_id = %d AND building_id = %d', array($teamId, $buildingId));
     $buildingExists = $result->fetch_array();
     $result->free();
     if ($buildingExists) {
         throw new Exception($this->_i18n->getMessage('stadiumenvironment_build_err_already_exists'));
     }
     // check required building
     if ($building['required_building_id']) {
         $result = $this->_db->querySelect('*', $dbPrefix . '_buildings_of_team', 'team_id = %d AND building_id = %d', array($teamId, $building['required_building_id']));
         $requiredBuildingExists = $result->fetch_array();
         $result->free();
         if (!$requiredBuildingExists) {
             throw new Exception($this->_i18n->getMessage('stadiumenvironment_build_err_requires_building'));
         }
     }
     // check premium costs
     if ($building['premiumfee'] > $user->premiumBalance) {
         throw new Exception($this->_i18n->getMessage('stadiumenvironment_build_err_premium_balance'));
     }
     // withdraw costs
     BankAccountDataService::debitAmount($this->_websoccer, $this->_db, $teamId, $building['costs'], 'building_construction_fee_subject', $building['name']);
     // place order
     $constructionDeadline = $this->_websoccer->getNowAsTimestamp() + $building['construction_time_days'] * 24 * 3600;
     $this->_db->queryInsert(array('building_id' => $buildingId, 'team_id' => $teamId, 'construction_deadline' => $constructionDeadline), $dbPrefix . '_buildings_of_team');
     // withdraw premium fee
     if ($building['premiumfee']) {
         PremiumDataService::debitAmount($this->_websoccer, $this->_db, $user->id, $building['premiumfee'], "order-building");
     }
     // credit fan popularity change
     if ($building['effect_fanpopularity'] != 0) {
         $result = $this->_db->querySelect('fanbeliebtheit', $dbPrefix . '_user', 'id = %d', $user->id, 1);
         $userinfo = $result->fetch_array();
         $result->free();
         $popularity = min(100, max(1, $building['effect_fanpopularity'] + $userinfo['fanbeliebtheit']));
         $this->_db->queryUpdate(array('fanbeliebtheit' => $popularity), $dbPrefix . '_user', 'id = %d', $user->id);
     }
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("stadiumenvironment_build_success"), ""));
     return null;
 }
 /**
  * Process buildings which cost per home match or which bring income per match.
  * 
  * @param MatchCompletedEvent $event event.
  */
 public static function creditAndDebitAfterHomeMatch(MatchCompletedEvent $event)
 {
     // do not consider friendlies
     if ($event->match->type == 'Freundschaft' || $event->match->homeTeam->isNationalTeam) {
         return;
     }
     $homeTeamId = $event->match->homeTeam->id;
     $sum = self::getBonusSumFromBuildings($event->websoccer, $event->db, 'effect_income', $homeTeamId);
     if ($sum > 0) {
         BankAccountDataService::creditAmount($event->websoccer, $event->db, $homeTeamId, $sum, 'stadiumenvironment_matchincome_subject', $event->websoccer->getConfig('projectname'));
     } else {
         BankAccountDataService::debitAmount($event->websoccer, $event->db, $homeTeamId, abs($sum), 'stadiumenvironment_costs_per_match_subject', $event->websoccer->getConfig('projectname'));
     }
 }
 private function creditSponsorPayments(SimulationTeam $team, $isHomeTeam, $teamIsWinner)
 {
     $columns = 'S.name AS sponsor_name, b_spiel,b_heimzuschlag,b_sieg,T.sponsor_spiele AS sponsor_matches';
     $fromTable = $this->_websoccer->getConfig('db_prefix') . '_verein AS T';
     $fromTable .= ' INNER JOIN ' . $this->_websoccer->getConfig('db_prefix') . '_sponsor AS S ON S.id = T.sponsor_id';
     $whereCondition = 'T.id = %d AND T.sponsor_spiele > 0';
     $result = $this->_db->querySelect($columns, $fromTable, $whereCondition, $team->id);
     $sponsor = $result->fetch_array();
     $result->free();
     if (isset($sponsor['sponsor_matches'])) {
         $amount = $sponsor['b_spiel'];
         if ($isHomeTeam) {
             $amount += $sponsor['b_heimzuschlag'];
         }
         if ($teamIsWinner) {
             $amount += $sponsor['b_sieg'];
         }
         BankAccountDataService::creditAmount($this->_websoccer, $this->_db, $team->id, $amount, 'match_sponsorpayment_subject', $sponsor['sponsor_name']);
         // update sponsor contract
         $updatecolums['sponsor_spiele'] = max(0, $sponsor['sponsor_matches'] - 1);
         if ($updatecolums['sponsor_spiele'] == 0) {
             $updatecolums['sponsor_id'] = '';
         }
         $whereCondition = 'id = %d';
         $fromTable = $this->_websoccer->getConfig('db_prefix') . '_verein';
         $this->_db->queryUpdate($updatecolums, $fromTable, $whereCondition, $team->id);
     }
 }
 private static function _executeEvent(WebSoccer $websoccer, DbConnection $db, $userId, $clubId, $event)
 {
     $notificationType = 'randomevent';
     $subject = $event['message'];
     // debit or credit money
     if ($event['effect'] == 'money') {
         $amount = $event['effect_money_amount'];
         $sender = $websoccer->getConfig('projectname');
         if ($amount > 0) {
             BankAccountDataService::creditAmount($websoccer, $db, $clubId, $amount, $subject, $sender);
         } else {
             BankAccountDataService::debitAmount($websoccer, $db, $clubId, $amount * (0 - 1), $subject, $sender);
         }
         // notification
         NotificationsDataService::createNotification($websoccer, $db, $userId, $subject, null, $notificationType, 'finances', null, $clubId);
         // execute on random player
     } else {
         // select random player from team
         $result = $db->querySelect('id, vorname, nachname, kunstname, w_frische, w_kondition, w_zufriedenheit', $websoccer->getConfig('db_prefix') . '_spieler', 'verein_id = %d AND gesperrt = 0 AND verletzt = 0 AND status = \'1\' ORDER BY RAND()', $clubId, 1);
         $player = $result->fetch_array();
         $result->free();
         if (!$player) {
             return;
         }
         // execute (get update column)
         switch ($event['effect']) {
             case 'player_injured':
                 $columns = array('verletzt' => $event['effect_blocked_matches']);
                 break;
             case 'player_blocked':
                 $columns = array('gesperrt' => $event['effect_blocked_matches']);
                 break;
             case 'player_happiness':
                 $columns = array('w_zufriedenheit' => max(1, min(100, $player['w_zufriedenheit'] + $event['effect_skillchange'])));
                 break;
             case 'player_fitness':
                 $columns = array('w_frische' => max(1, min(100, $player['w_frische'] + $event['effect_skillchange'])));
                 break;
             case 'player_stamina':
                 $columns = array('w_kondition' => max(1, min(100, $player['w_kondition'] + $event['effect_skillchange'])));
                 break;
         }
         // update player
         if (!isset($columns)) {
             return;
         }
         $db->queryUpdate($columns, $websoccer->getConfig('db_prefix') . '_spieler', 'id = %d', $player['id']);
         // create notification
         $playerName = strlen($player['kunstname']) ? $player['kunstname'] : $player['vorname'] . ' ' . $player['nachname'];
         NotificationsDataService::createNotification($websoccer, $db, $userId, $subject, array('playername' => $playerName), $notificationType, 'player', 'id=' . $player['id'], $clubId);
     }
 }