/**
  * (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";
 }
 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_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";
 }
 /**
  * (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"]);
 }
 /**
  * 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);
 }
             $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']);
     }
 }
 /**
  * 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);
     }
 }
 /**
  * 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']);
         }
     }
 }
 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']);
     }
 }