/**
  * (non-PHPdoc)
  * @see IModel::getTemplateParameters()
  */
 public function getTemplateParameters()
 {
     $teamId = (int) $this->_websoccer->getRequestParameter('id');
     if ($teamId < 1) {
         throw new Exception($this->_i18n->getMessage(MSG_KEY_ERROR_PAGENOTFOUND));
     }
     $team = TeamsDataService::getTeamById($this->_websoccer, $this->_db, $teamId);
     if (!isset($team['team_id'])) {
         throw new Exception($this->_i18n->getMessage(MSG_KEY_ERROR_PAGENOTFOUND));
     }
     // get current season
     $result = $this->_db->querySelect('id', $this->_websoccer->getConfig('db_prefix') . '_saison', 'liga_id = %d AND beendet = \'0\' ORDER BY name DESC', $team['team_league_id'], 1);
     $season = $result->fetch_array();
     $result->free();
     // get records
     $history = array();
     if ($season) {
         $columns = array('H.matchday' => 'matchday', 'H.rank' => 'rank');
         $fromTable = $this->_websoccer->getConfig('db_prefix') . '_leaguehistory AS H';
         $result = $this->_db->querySelect('matchday, rank', $fromTable, 'season_id = %d AND team_id = %s ORDER BY matchday ASC', array($season['id'], $team['team_id']));
         while ($historyRecord = $result->fetch_array()) {
             $history[] = $historyRecord;
         }
         $result->free();
     }
     // count teams in league
     $result = $this->_db->querySelect('COUNT(*) AS cnt', $this->_websoccer->getConfig('db_prefix') . '_verein', 'liga_id = %d AND status = \'1\'', $team['team_league_id'], 1);
     $teams = $result->fetch_array();
     $result->free();
     return array('teamName' => $team['team_name'], 'history' => $history, 'noOfTeamsInLeague' => $teams['cnt'], 'leagueid' => $team['team_league_id']);
 }
 /**
  * (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;
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     $user = $this->_websoccer->getUser();
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     $team = TeamsDataService::getTeamById($this->_websoccer, $this->_db, $clubId);
     // 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");
     }
     $this->_db->queryUpdate(array("captain_id" => $parameters["id"]), $this->_websoccer->getConfig("db_prefix") . "_verein", "id = %d", $clubId);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("myteam_player_select_as_captain_success"), ""));
     // check if captain has been changed and show disappointment
     if ($team["captain_id"] && $team["captain_id"] != $parameters["id"]) {
         $oldPlayer = PlayersDataService::getPlayerById($this->_websoccer, $this->_db, $team["captain_id"]);
         // maybe player has moved to new team, then just ignore it
         if ($oldPlayer["team_id"] == $clubId) {
             $newSatisfaction = round($oldPlayer["player_strength_satisfaction"] * 0.6);
             $this->_db->queryUpdate(array("w_zufriedenheit" => $newSatisfaction), $this->_websoccer->getConfig("db_prefix") . "_spieler", "id = %d", $oldPlayer["player_id"]);
             $playername = strlen($oldPlayer["player_pseudonym"]) ? $oldPlayer["player_pseudonym"] : $oldPlayer["player_firstname"] . " " . $oldPlayer["player_lastname"];
             $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_WARNING, $this->_i18n->getMessage("myteam_player_select_as_captain_warning_old_captain", $playername), ""));
         }
     }
     return null;
 }
 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 IModel::getTemplateParameters()
  */
 public function getTemplateParameters()
 {
     $teamId = (int) $this->_websoccer->getRequestParameter('id');
     if ($teamId < 1) {
         throw new Exception($this->_i18n->getMessage(MSG_KEY_ERROR_PAGENOTFOUND));
     }
     $team = TeamsDataService::getTeamById($this->_websoccer, $this->_db, $teamId);
     if (!isset($team['team_id'])) {
         throw new Exception($this->_i18n->getMessage(MSG_KEY_ERROR_PAGENOTFOUND));
     }
     $stadium = StadiumsDataService::getStadiumByTeamId($this->_websoccer, $this->_db, $teamId);
     // compute strength level of national team
     if ($team['is_nationalteam']) {
         $dbPrefix = $this->_websoccer->getConfig('db_prefix');
         $result = $this->_db->querySelect('AVG(P.w_staerke) AS avgstrength', $dbPrefix . '_spieler AS P INNER JOIN ' . $dbPrefix . '_nationalplayer AS NP ON P.id = NP.player_id', 'NP.team_id = %d', $team['team_id']);
         $players = $result->fetch_array();
         $result->free();
         if ($players) {
             $team['team_strength'] = $players['avgstrength'];
         }
     }
     if (!$team['is_nationalteam']) {
         $playerfacts = $this->getPlayerFacts($teamId);
     } else {
         $playerfacts = array();
     }
     $team['victories'] = $this->getVictories($team['team_id'], $team['team_league_id']);
     $team['cupvictories'] = $this->getCupVictories($team['team_id']);
     return array('team' => $team, 'stadium' => $stadium, 'playerfacts' => $playerfacts);
 }
 public function executeAction($parameters)
 {
     // check if feature is enabled
     if (!$this->_websoccer->getConfig("transfermarket_enabled")) {
         return NULL;
     }
     $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 if player is already on market
     if ($player["player_transfermarket"]) {
         throw new Exception($this->_i18n->getMessage("sell_player_already_on_list"));
     }
     // check if player is borrowed or lendable. User should not come to this point, so message is not important.
     if ($player["lending_fee"] > 0) {
         throw new Exception($this->_i18n->getMessage("lending_err_alreadyoffered"));
     }
     // check violation of minimum team size
     $teamSize = TeamsDataService::getTeamSize($this->_websoccer, $this->_db, $clubId);
     if ($teamSize <= $this->_websoccer->getConfig("transfermarket_min_teamsize")) {
         throw new Exception($this->_i18n->getMessage("sell_player_teamsize_too_small", $teamSize));
     }
     $minBidBoundary = round($player["player_marketvalue"] / 2);
     if ($parameters["min_bid"] < $minBidBoundary) {
         throw new Exception($this->_i18n->getMessage("sell_player_min_bid_too_low"));
     }
     $this->updatePlayer($player["player_id"], $parameters["min_bid"]);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("sell_player_success"), ""));
     return "transfermarket";
 }
 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);
     // check if user has a club
     if ($clubId < 1) {
         throw new Exception($this->_i18n->getMessage("error_action_required_team"));
     }
     // check if date is valid (might be manipulated)
     $tooLateBoundary = $this->_websoccer->getNowAsTimestamp() + 3600 * 24 * (1 + $this->_websoccer->getConfig("youth_matchrequest_max_futuredays"));
     $validTimes = explode(",", $this->_websoccer->getConfig("youth_matchrequest_allowedtimes"));
     // check valid times (remove white spaces)
     $timeIsValid = FALSE;
     $matchTime = date("H:i", $parameters["matchdate"]);
     foreach ($validTimes as $validTime) {
         if ($matchTime == trim($validTime)) {
             $timeIsValid = TRUE;
             break;
         }
     }
     if (!$timeIsValid || $parameters["matchdate"] > $tooLateBoundary) {
         throw new Exception($this->_i18n->getMessage("youthteam_matchrequest_create_err_invaliddate"));
     }
     // check maximum number of open requests
     $fromTable = $this->_websoccer->getConfig("db_prefix") . "_youthmatch_request";
     $result = $this->_db->querySelect("COUNT(*) AS hits", $fromTable, "team_id = %d", $clubId);
     $requests = $result->fetch_array();
     $result->free();
     $maxNoOfRequests = (int) $this->_websoccer->getConfig("youth_matchrequest_max_open_requests");
     if ($requests && $requests["hits"] >= $maxNoOfRequests) {
         throw new Exception($this->_i18n->getMessage("youthteam_matchrequest_create_err_too_many_open_requests", $maxNoOfRequests));
     }
     // check if reward can be paid
     if ($parameters["reward"]) {
         $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
         if ($team["team_budget"] <= $parameters["reward"]) {
             throw new Exception($this->_i18n->getMessage("youthteam_matchrequest_create_err_budgetnotenough"));
         }
     }
     // check if 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 per day constraint
     $maxMatchesPerDay = $this->_websoccer->getConfig("youth_match_maxperday");
     if (YouthMatchesDataService::countMatchesOfTeamOnSameDay($this->_websoccer, $this->_db, $clubId, $parameters["matchdate"]) >= $maxMatchesPerDay) {
         throw new Exception($this->_i18n->getMessage("youthteam_matchrequest_err_maxperday_violated", $maxMatchesPerDay));
     }
     // create request
     $columns = array("team_id" => $clubId, "matchdate" => $parameters["matchdate"], "reward" => $parameters["reward"]);
     $this->_db->queryInsert($columns, $fromTable);
     // create success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("youthteam_matchrequest_create_success"), ""));
     return "youth-matchrequests";
 }
 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)
 {
     $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");
     }
     // if player is not happy at club, he does not want to extend at all
     $satisfaction = $player["player_strength_satisfaction"];
     if ($satisfaction < MINIMUM_SATISFACTION_FOR_EXTENSION) {
         throw new Exception($this->_i18n->getMessage("extend-contract_player_is_unhappy"));
     }
     // check if player is already on market
     if ($player["player_transfermarket"]) {
         throw new Exception($this->_i18n->getMessage("sell_player_already_on_list"));
     }
     // no salary decrease
     if ($parameters["salary"] < $player["player_contract_salary"]) {
         throw new Exception($this->_i18n->getMessage("extend-contract_lower_than_current_salary"));
     }
     $averageSalary = $this->getAverageSalary($player["player_strength"]);
     // if salary is already higher than average, then just expect 10% more
     if ($player["player_contract_salary"] > $averageSalary) {
         $salaryFactor = 1.1;
     } else {
         // make minimum salary dependent on happiness
         $salaryFactor = (200 - $satisfaction) / 100;
     }
     $salaryFactor = max(1.1, $salaryFactor);
     $minSalary = round($player["player_contract_salary"] * $salaryFactor);
     // the salary should be at least 90% of the average, except if this would douple the salary
     if ($averageSalary < $parameters["salary"] * 2) {
         $minSalaryOfAverage = round(0.9 * $averageSalary);
         $minSalary = max($minSalary, $minSalaryOfAverage);
     }
     if ($parameters["salary"] < $minSalary) {
         // decrease satisfaction
         $this->decreaseSatisfaction($player["player_id"], $player["player_strength_satisfaction"]);
         throw new Exception($this->_i18n->getMessage("extend-contract_salary_too_low"));
     }
     // check if club can pay this salary
     TeamsDataService::validateWhetherTeamHasEnoughBudgetForSalaryBid($this->_websoccer, $this->_db, $this->_i18n, $clubId, $parameters["salary"]);
     // check goal bonus
     $minGoalBonus = $player["player_contract_goalbonus"] * 1.3;
     if ($parameters["goal_bonus"] < $minGoalBonus) {
         throw new Exception($this->_i18n->getMessage("extend-contract_goalbonus_too_low"));
     }
     $this->updatePlayer($player["player_id"], $player["player_strength_satisfaction"], $parameters["salary"], $parameters["goal_bonus"], $parameters["matches"]);
     // reset inactivity
     UserInactivityDataService::resetContractExtensionField($this->_websoccer, $this->_db, $user->id);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("extend-contract_success"), ""));
     return null;
 }
 /**
  * (non-PHPdoc)
  * @see IModel::getTemplateParameters()
  */
 public function getTemplateParameters()
 {
     $teamId = $this->_websoccer->getUser()->getClubId($this->_websoccer, $this->_db);
     $captain_id = TeamsDataService::getTeamCaptainIdOfTeam($this->_websoccer, $this->_db, $teamId);
     $players = array();
     if ($teamId > 0) {
         $players = PlayersDataService::getPlayersOfTeamById($this->_websoccer, $this->_db, $teamId);
     }
     return array("players" => $players, "captain_id" => $captain_id);
 }
 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 static function getSponsorOffers(WebSoccer $websoccer, DbConnection $db, $teamId)
 {
     $team = TeamsDataService::getTeamSummaryById($websoccer, $db, $teamId);
     $teamRank = TeamsDataService::getTableRankOfTeam($websoccer, $db, $teamId);
     $columns["S.id"] = "sponsor_id";
     $columns["S.name"] = "name";
     $columns["S.b_spiel"] = "amount_match";
     $columns["S.b_heimzuschlag"] = "amount_home_bonus";
     $columns["S.b_sieg"] = "amount_win";
     $columns["S.b_meisterschaft"] = "amount_championship";
     $fromTable = $websoccer->getConfig("db_prefix") . "_sponsor AS S";
     $whereCondition = "S.liga_id = %d AND (S.min_platz = 0 OR S.min_platz >= %d)" . " AND (S.max_teams <= 0 OR S.max_teams > (SELECT COUNT(*) FROM " . $websoccer->getConfig("db_prefix") . "_verein AS T WHERE T.sponsor_id = S.id AND T.sponsor_spiele > 0))" . " ORDER BY S.b_spiel DESC";
     $parameters = array($team["team_league_id"], $teamRank);
     return $db->queryCachedSelect($columns, $fromTable, $whereCondition, $parameters, 20);
 }
 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";
 }
 public function executeAction($parameters)
 {
     // check if feature is enabled
     if (!$this->_websoccer->getConfig("transferoffers_enabled")) {
         return;
     }
     $clubId = $this->_websoccer->getUser()->getClubId($this->_websoccer, $this->_db);
     // get offer information
     $result = $this->_db->querySelect("*", $this->_websoccer->getConfig("db_prefix") . "_transfer_offer", "id = %d AND rejected_date = 0 AND admin_approval_pending = '0'", $parameters["id"]);
     $offer = $result->fetch_array();
     $result->free();
     $player = PlayersDataService::getPlayerById($this->_websoccer, $this->_db, $offer["player_id"]);
     // check if player is already on transfer market
     if ($player["player_transfermarket"]) {
         throw new Exception($this->_i18n->getMessage("transferoffer_err_unsellable"));
     }
     // check exchange players
     if ($offer["offer_player1"] || $offer["offer_player2"]) {
         $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
         if ($offer["offer_player1"]) {
             $this->checkExchangePlayer($offer["offer_player1"], $offer["sender_user_id"], $team["team_budget"]);
         }
         if ($offer["offer_player2"]) {
             $this->checkExchangePlayer($offer["offer_player2"], $offer["sender_user_id"], $team["team_budget"]);
         }
     }
     // check if team is above minimum number of players.
     $teamSize = TeamsDataService::getTeamSize($this->_websoccer, $this->_db, $clubId);
     if ($teamSize < $this->_websoccer->getConfig("transfermarket_min_teamsize")) {
         throw new Exception($this->_i18n->getMessage("sell_player_teamsize_too_small", $teamSize));
     }
     // mark offer as pending
     if ($this->_websoccer->getConfig("transferoffers_adminapproval_required")) {
         $this->_db->queryUpdate(array("admin_approval_pending" => "1"), $this->_websoccer->getConfig("db_prefix") . "_transfer_offer", "id = %d", $parameters["id"]);
         $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("transferoffer_accepted_title"), $this->_i18n->getMessage("transferoffer_accepted_message_approvalpending")));
         // execute transfer
     } else {
         DirectTransfersDataService::executeTransferFromOffer($this->_websoccer, $this->_db, $parameters["id"]);
         // show success message
         $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("transferoffer_accepted_title"), $this->_i18n->getMessage("transferoffer_accepted_message")));
     }
     return null;
 }
 /**
  * (non-PHPdoc)
  * @see IActionController::executeAction()
  */
 public function executeAction($parameters)
 {
     // check if feature is enabled
     if (!$this->_websoccer->getConfig('rename_club_enabled')) {
         throw new Exceltion("feature is disabled");
     }
     $user = $this->_websoccer->getUser();
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
     if (!$team) {
         return null;
     }
     // rename club
     $short = strtoupper($parameters['kurz']);
     $this->_db->queryUpdate(array('name' => $parameters['name'], 'kurz' => $short), $this->_websoccer->getConfig('db_prefix') . '_verein', 'id = %d', $clubId);
     // rename stadium
     $this->_db->queryUpdate(array('S.name' => $parameters['stadium']), $this->_websoccer->getConfig('db_prefix') . '_verein AS C INNER JOIN ' . $this->_websoccer->getConfig('db_prefix') . '_stadion AS S ON S.id = C.stadion_id', 'C.id = %d', $clubId);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("rename-club_success"), ""));
     return 'league';
 }
 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 it is own player
     $player = PlayersDataService::getPlayerById($this->_websoccer, $this->_db, $parameters["id"]);
     if ($clubId != $player["team_id"]) {
         throw new Exception($this->_i18n->getMessage("lending_err_notownplayer"));
     }
     // check if player is borrowed by user
     if ($player["lending_owner_id"] > 0) {
         throw new Exception($this->_i18n->getMessage("lending_err_borrowed_player"));
     }
     // check if player is already offered for lending
     if ($player["lending_fee"] > 0) {
         throw new Exception($this->_i18n->getMessage("lending_err_alreadyoffered"));
     }
     // check if player is on transfermarket
     if ($player["player_transfermarket"] > 0) {
         throw new Exception($this->_i18n->getMessage("lending_err_on_transfermarket"));
     }
     // check violation of minimum team size
     $teamSize = TeamsDataService::getTeamSize($this->_websoccer, $this->_db, $clubId);
     if ($teamSize <= $this->_websoccer->getConfig("transfermarket_min_teamsize")) {
         throw new Exception($this->_i18n->getMessage("lending_err_teamsize_too_small", $teamSize));
     }
     // remaining contract is too short
     $minBidBoundary = round($player["player_marketvalue"] / 2);
     if ($player["player_contract_matches"] <= $this->_websoccer->getConfig("lending_matches_min")) {
         throw new Exception($this->_i18n->getMessage("lending_err_contract_too_short"));
     }
     $this->updatePlayer($player["player_id"], $parameters["fee"]);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("lend_player_success"), ""));
     return "myteam";
 }
 /**
  * (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);
     // check if it is 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_err_notownplayer"));
     }
     // check if old enough
     if ($player["age"] < $this->_websoccer->getConfig("youth_min_age_professional")) {
         throw new Exception($this->_i18n->getMessage("youthteam_makeprofessional_err_tooyoung", $this->_websoccer->getConfig("youth_min_age_professional")));
     }
     // validate main position (must be in compliance with general position)
     if ($player["position"] == "Torwart") {
         $validPositions = array("T");
     } elseif ($player["position"] == "Abwehr") {
         $validPositions = array("LV", "IV", "RV");
     } elseif ($player["position"] == "Mittelfeld") {
         $validPositions = array("LM", "RM", "DM", "OM", "ZM");
     } else {
         $validPositions = array("LS", "RS", "MS");
     }
     if (!in_array($parameters["mainposition"], $validPositions)) {
         throw new Exception($this->_i18n->getMessage("youthteam_makeprofessional_err_invalidmainposition"));
     }
     // check if team can afford salary
     $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
     if ($team["team_budget"] <= TeamsDataService::getTotalPlayersSalariesOfTeam($this->_websoccer, $this->_db, $clubId)) {
         throw new Exception($this->_i18n->getMessage("youthteam_makeprofessional_err_budgettooless"));
     }
     $this->createPlayer($player, $parameters["mainposition"]);
     // success message
     $this->_websoccer->addFrontMessage(new FrontMessage(MESSAGE_TYPE_SUCCESS, $this->_i18n->getMessage("youthteam_makeprofessional_success"), ""));
     return "myteam";
 }
 /**
  * (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";
 }
 /**
  * (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";
 }
 public function getTemplateParameters()
 {
     $fromTable = $this->_websoccer->getConfig("db_prefix") . "_user";
     $user = $this->_websoccer->getUser();
     // select general information
     $columns = "fanbeliebtheit AS user_popularity, highscore AS user_highscore";
     $whereCondition = "id = %d";
     $result = $this->_db->querySelect($columns, $fromTable, $whereCondition, $user->id, 1);
     $userinfo = $result->fetch_array();
     $result->free();
     $clubId = $user->getClubId($this->_websoccer, $this->_db);
     // get team info
     $team = null;
     if ($clubId > 0) {
         $team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $clubId);
     }
     // unread messages
     $unseenMessages = MessagesDataService::countUnseenInboxMessages($this->_websoccer, $this->_db);
     // unseen notifications
     $unseenNotifications = NotificationsDataService::countUnseenNotifications($this->_websoccer, $this->_db, $user->id, $clubId);
     return array("profile" => $userinfo, "userteam" => $team, "unseenMessages" => $unseenMessages, "unseenNotifications" => $unseenNotifications);
 }
 /**
  * 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";
 }
 /**
  * Debits specified amount from team's account (TAKING money).
  * 
  * @param WebSoccer $websoccer Application context.
  * @param DbConnection $db DB connection.
  * @param int $teamId ID of team
  * @param int $amount Positive amount to debit. If 0, no statement will be created.
  * @param string $subject message key or untranslated message to display to user.
  * @param string $sender Name of sender.
  * @throws Exception if amount is negative or team could not be found.
  */
 public static function debitAmount(WebSoccer $websoccer, DbConnection $db, $teamId, $amount, $subject, $sender)
 {
     if ($amount == 0) {
         return;
     }
     $team = TeamsDataService::getTeamSummaryById($websoccer, $db, $teamId);
     if (!isset($team["team_id"])) {
         throw new Exception("team not found: " . $teamId);
     }
     if ($amount < 0) {
         throw new Exception("amount illegal: " . $amount);
     }
     $amount = 0 - $amount;
     self::createTransaction($websoccer, $db, $team, $teamId, $amount, $subject, $sender);
 }
 public function getTemplateParameters()
 {
     $query = $this->_websoccer->getRequestParameter("query");
     $teams = TeamsDataService::findTeamNames($this->_websoccer, $this->_db, $query);
     return array("items" => $teams);
 }
 /**
  * (non-PHPdoc)
  * @see IModel::getTemplateParameters()
  */
 public function getTemplateParameters()
 {
     return array("countries" => TeamsDataService::getTeamsWithoutUser($this->_websoccer, $this->_db));
 }
 /**
  * (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;
 }
 /**
  * (non-PHPdoc)
  * @see IModel::getTemplateParameters()
  */
 public function getTemplateParameters()
 {
     // get team players
     if ($this->_nationalteam) {
         $clubId = NationalteamsDataService::getNationalTeamManagedByCurrentUser($this->_websoccer, $this->_db);
     } else {
         $clubId = $this->_websoccer->getUser()->getClubId($this->_websoccer, $this->_db);
     }
     // next x matches
     $nextMatches = MatchesDataService::getNextMatches($this->_websoccer, $this->_db, $clubId, $this->_websoccer->getConfig('formation_max_next_matches'));
     if (!count($nextMatches)) {
         throw new Exception($this->_i18n->getMessage('next_match_block_no_nextmatch'));
     }
     // currently selected match
     $matchId = $this->_websoccer->getRequestParameter('id');
     if (!$matchId) {
         $matchinfo = $nextMatches[0];
     } else {
         foreach ($nextMatches as $nextMatch) {
             if ($nextMatch['match_id'] == $matchId) {
                 $matchinfo = $nextMatch;
                 break;
             }
         }
     }
     if (!isset($matchinfo)) {
         throw new Exception('illegal match id');
     }
     $players = null;
     if ($clubId > 0) {
         if ($this->_nationalteam) {
             $players = NationalteamsDataService::getNationalPlayersOfTeamByPosition($this->_websoccer, $this->_db, $clubId);
         } else {
             $players = PlayersDataService::getPlayersOfTeamByPosition($this->_websoccer, $this->_db, $clubId, 'DESC', count($matchinfo) && $matchinfo['match_type'] == 'cup', isset($matchinfo['match_type']) && $matchinfo['match_type'] != 'friendly');
         }
     }
     // load template
     if ($this->_websoccer->getRequestParameter('templateid')) {
         $formation = FormationDataService::getFormationByTemplateId($this->_websoccer, $this->_db, $clubId, $this->_websoccer->getRequestParameter('templateid'));
     } else {
         // get previously saved formation and tactic
         $formation = FormationDataService::getFormationByTeamId($this->_websoccer, $this->_db, $clubId, $matchinfo['match_id']);
     }
     for ($benchNo = 1; $benchNo <= 5; $benchNo++) {
         if ($this->_websoccer->getRequestParameter('bench' . $benchNo)) {
             $formation['bench' . $benchNo] = $this->_websoccer->getRequestParameter('bench' . $benchNo);
         } else {
             if (!isset($formation['bench' . $benchNo])) {
                 $formation['bench' . $benchNo] = '';
             }
         }
     }
     for ($subNo = 1; $subNo <= 3; $subNo++) {
         if ($this->_websoccer->getRequestParameter('sub' . $subNo . '_out')) {
             $formation['sub' . $subNo . '_out'] = $this->_websoccer->getRequestParameter('sub' . $subNo . '_out');
             $formation['sub' . $subNo . '_in'] = $this->_websoccer->getRequestParameter('sub' . $subNo . '_in');
             $formation['sub' . $subNo . '_minute'] = $this->_websoccer->getRequestParameter('sub' . $subNo . '_minute');
             $formation['sub' . $subNo . '_condition'] = $this->_websoccer->getRequestParameter('sub' . $subNo . '_condition');
             $formation['sub' . $subNo . '_position'] = $this->_websoccer->getRequestParameter('sub' . $subNo . '_position');
         } else {
             if (!isset($formation['sub' . $subNo . '_out'])) {
                 $formation['sub' . $subNo . '_out'] = '';
                 $formation['sub' . $subNo . '_in'] = '';
                 $formation['sub' . $subNo . '_minute'] = '';
                 $formation['sub' . $subNo . '_condition'] = '';
                 $formation['sub' . $subNo . '_position'] = '';
             }
         }
     }
     $setup = $this->getFormationSetup($formation);
     // select players from team by criteria
     $criteria = $this->_websoccer->getRequestParameter('preselect');
     if ($criteria !== NULL) {
         if ($criteria == 'strongest') {
             $sortColumn = 'w_staerke';
         } elseif ($criteria == 'freshest') {
             $sortColumn = 'w_frische';
         } else {
             $sortColumn = 'w_zufriedenheit';
         }
         $proposedPlayers = FormationDataService::getFormationProposalForTeamId($this->_websoccer, $this->_db, $clubId, $setup['defense'], $setup['dm'], $setup['midfield'], $setup['om'], $setup['striker'], $setup['outsideforward'], $sortColumn, 'DESC', $this->_nationalteam, isset($matchinfo['match_type']) && $matchinfo['match_type'] == 'cup');
         for ($playerNo = 1; $playerNo <= 11; $playerNo++) {
             $playerIndex = $playerNo - 1;
             if (isset($proposedPlayers[$playerIndex])) {
                 $formation['player' . $playerNo] = $proposedPlayers[$playerIndex]['id'];
                 $formation['player' . $playerNo . '_pos'] = $proposedPlayers[$playerIndex]['position'];
             }
         }
         // clear bench (prevents duplicate players)
         for ($benchNo = 1; $benchNo <= 5; $benchNo++) {
             $formation['bench' . $benchNo] = '';
         }
         for ($subNo = 1; $subNo <= 3; $subNo++) {
             $formation['sub' . $subNo . '_out'] = '';
             $formation['sub' . $subNo . '_in'] = '';
             $formation['sub' . $subNo . '_minute'] = '';
             $formation['sub' . $subNo . '_condition'] = '';
             $formation['sub' . $subNo . '_position'] = '';
         }
     }
     // free kick taker
     if ($this->_websoccer->getRequestParameter('freekickplayer')) {
         $formation['freekickplayer'] = $this->_websoccer->getRequestParameter('freekickplayer');
     } else {
         if (!isset($formation['freekickplayer'])) {
             $formation['freekickplayer'] = '';
         }
     }
     // tactical options
     if ($this->_websoccer->getRequestParameter('offensive')) {
         $formation['offensive'] = $this->_websoccer->getRequestParameter('offensive');
     } else {
         if (!isset($formation['offensive'])) {
             $formation['offensive'] = 40;
         }
     }
     if ($this->_websoccer->getRequestParameter('longpasses')) {
         $formation['longpasses'] = $this->_websoccer->getRequestParameter('longpasses');
     }
     if ($this->_websoccer->getRequestParameter('counterattacks')) {
         $formation['counterattacks'] = $this->_websoccer->getRequestParameter('counterattacks');
     }
     for ($playerNo = 1; $playerNo <= 11; $playerNo++) {
         // set player from request
         if ($this->_websoccer->getRequestParameter('player' . $playerNo)) {
             $formation['player' . $playerNo] = $this->_websoccer->getRequestParameter('player' . $playerNo);
             $formation['player' . $playerNo . '_pos'] = $this->_websoccer->getRequestParameter('player' . $playerNo . '_pos');
             // set to 0 if no previous formation is available
         } else {
             if (!isset($formation['player' . $playerNo])) {
                 $formation['player' . $playerNo] = '';
                 $formation['player' . $playerNo . '_pos'] = '';
             }
         }
     }
     return array('nextMatches' => $nextMatches, 'next_match' => $matchinfo, 'previous_matches' => MatchesDataService::getPreviousMatches($matchinfo, $this->_websoccer, $this->_db), 'players' => $players, 'formation' => $formation, 'setup' => $setup, 'captain_id' => TeamsDataService::getTeamCaptainIdOfTeam($this->_websoccer, $this->_db, $clubId));
 }
 /**
  * (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";
 }
 if ($admin['r_demo']) {
     $err[] = $i18n->getMessage('validationerror_no_changes_as_demo');
 }
 if (isset($err)) {
     include 'validationerror.inc.php';
 } else {
     // strengths for player generation
     $strengths['strength'] = $_POST['entity_player_w_staerke'];
     $strengths['technique'] = $_POST['entity_player_w_technik'];
     $strengths['stamina'] = $_POST['entity_player_w_kondition'];
     $strengths['freshness'] = $_POST['entity_player_w_frische'];
     $strengths['satisfaction'] = $_POST['entity_player_w_zufriedenheit'];
     $teamIds = explode(',', $_POST['teamids']);
     foreach ($teamIds as $teamId) {
         // get team info
         $team = TeamsDataService::getTeamSummaryById($website, $db, $teamId);
         // update team
         $teamcolumns = array('user_id' => '', 'captain_id' => '', 'finanz_budget' => !empty($_POST['minbudget']) ? max($_POST['minbudget'], $team['team_budget']) : $team['team_budget']);
         $db->queryUpdate($teamcolumns, $website->getConfig('db_prefix') . '_verein', 'id = %d', $teamId);
         // disable user
         if (isset($_POST['disableusers']) && $_POST['disableusers']) {
             $db->queryUpdate(array('status' => '0'), $website->getConfig('db_prefix') . '_user', 'id = %d', $team['user_id']);
         }
         // send message to user
         if (!empty($_POST['message_subject']) && !empty($_POST['message_content'])) {
             $db->queryInsert(array('empfaenger_id' => $team['user_id'], 'absender_name' => $website->getConfig('projectname'), 'absender_id' => '', 'datum' => $website->getNowAsTimestamp(), 'betreff' => trim($_POST['message_subject']), 'nachricht' => trim($_POST['message_content'])), $website->getConfig('db_prefix') . '_briefe');
         }
         // count and update players
         $positionsCount = array();
         $positionsCount['T'] = 0;
         $positionsCount['LV'] = 0;