/**
  * Creates badge assignment.
  *
  * @param WebSoccer $websoccer Application context.
  * @param DbConnection $db DB connection.
  * @param int $userId ID of user.
  * @param int $badgeId ID od badge.
  */
 public static function awardBadge(WebSoccer $websoccer, DbConnection $db, $userId, $badgeId)
 {
     $badgeUserTable = $websoccer->getConfig('db_prefix') . '_badge_user';
     // create assignment
     $db->queryInsert(array('user_id' => $userId, 'badge_id' => $badgeId, 'date_rewarded' => $websoccer->getNowAsTimestamp()), $badgeUserTable);
     // notify lucky user
     NotificationsDataService::createNotification($websoccer, $db, $userId, 'badge_notification', null, 'badge', 'user', 'id=' . $userId);
 }
 /**
  * Marks user as absent, makes his teams managable by deputy and sends deputy notification about it.
  * 
  * @param WebSoccer $websoccer Application context.
  * @param DbConnection $db DB connection.
  * @param int $userId ID of user who is absent.
  * @param int $deputyId ID of user's deputy during absence.
  * @param int $days Number of days to be absent.
  */
 public static function makeUserAbsent(WebSoccer $websoccer, DbConnection $db, $userId, $deputyId, $days)
 {
     // create absence record
     $fromDate = $websoccer->getNowAsTimestamp();
     $toDate = $fromDate + 24 * 3600 * $days;
     $db->queryInsert(array('user_id' => $userId, 'deputy_id' => $deputyId, 'from_date' => $fromDate, 'to_date' => $toDate), $websoccer->getConfig('db_prefix') . '_userabsence');
     // update manager reference of managed teams
     $db->queryUpdate(array('user_id' => $deputyId, 'user_id_actual' => $userId), $websoccer->getConfig('db_prefix') . '_verein', 'user_id = %d', $userId);
     // create notification for deputy
     $user = UsersDataService::getUserById($websoccer, $db, $userId);
     NotificationsDataService::createNotification($websoccer, $db, $deputyId, 'absence_notification', array('until' => $toDate, 'user' => $user['nick']), 'absence', 'user');
 }
 /**
  * Creates a new unseen notification about any event which shall catch the user's attention.
  * 
  * @param WebSoccer $websoccer application context.
  * @param DbConnection $db DB connection.
  * @param int $userId ID of notification receiver.
  * @param string $messageKey key of message to display. Can contain place holders in form of {myplaceholder}.
  * @param array $messageData values of placeholder as an assoc. array. Array keys are message place holders.
  * @param string $type Optional. Type of notification as a string ID. Can be used for displaying icons or similar in the view layer.
  * @param string $targetPageId Optional. ID of page to which a link shall be targetting.
  * @param string $targetPageQueryString Optional. Query string to append to the target page link.
  * @param int $teamId Optional. ID of team to which this notification is assigned.
  */
 public static function createNotification(WebSoccer $websoccer, DbConnection $db, $userId, $messageKey, $messageData = null, $type = null, $targetPageId = null, $targetPageQueryString = null, $teamId = null)
 {
     $columns = array('user_id' => $userId, 'eventdate' => $websoccer->getNowAsTimestamp(), 'message_key' => $messageKey);
     if ($messageData != null) {
         $columns['message_data'] = json_encode($messageData);
     }
     if ($type != null) {
         $columns['eventtype'] = $type;
     }
     if ($targetPageId != null) {
         $columns['target_pageid'] = $targetPageId;
     }
     if ($targetPageQueryString != null) {
         $columns['target_querystr'] = $targetPageQueryString;
     }
     if ($teamId != null) {
         $columns['team_id'] = $teamId;
     }
     $db->queryInsert($columns, $websoccer->getConfig('db_prefix') . '_notification');
 }
 public static function getUserInactivity(WebSoccer $websoccer, DbConnection $db, $userId)
 {
     $columns["id"] = "id";
     $columns["login"] = "******";
     $columns["login_check"] = "login_check";
     $columns["aufstellung"] = "tactics";
     $columns["transfer"] = "transfer";
     $columns["transfer_check"] = "transfer_check";
     $columns["vertragsauslauf"] = "contractextensions";
     $fromTable = $websoccer->getConfig("db_prefix") . "_user_inactivity";
     $whereCondition = "user_id = %d";
     $parameters = $userId;
     $result = $db->querySelect($columns, $fromTable, $whereCondition, $parameters, 1);
     $inactivity = $result->fetch_array();
     $result->free();
     // create new entry
     if (!$inactivity) {
         $newcolumns["user_id"] = $userId;
         $db->queryInsert($newcolumns, $fromTable);
         return self::getUserInactivity($websoccer, $db, $userId);
     }
     return $inactivity;
 }
 private static function createTransaction(WebSoccer $websoccer, DbConnection $db, $team, $teamId, $amount, $subject, $sender)
 {
     // ignore transaction if team is without user and option is enabled
     if (!$team["user_id"] && $websoccer->getConfig("no_transactions_for_teams_without_user")) {
         return;
     }
     // create transaction
     $fromTable = $websoccer->getConfig("db_prefix") . "_konto";
     $columns["verein_id"] = $teamId;
     $columns["absender"] = $sender;
     $columns["betrag"] = $amount;
     $columns["datum"] = $websoccer->getNowAsTimestamp();
     $columns["verwendung"] = $subject;
     $db->queryInsert($columns, $fromTable);
     // update team budget
     $newBudget = $team["team_budget"] + $amount;
     $updateColumns["finanz_budget"] = $newBudget;
     $fromTable = $websoccer->getConfig("db_prefix") . "_verein";
     $whereCondition = "id = %d";
     $parameters = $teamId;
     $db->queryUpdate($updateColumns, $fromTable, $whereCondition, $parameters);
 }
 /**
  * Creates a payment log entry and credits premium balance according to available price options.
  * 
  * @param WebSoccer $websoccer Application context.
  * @param DbConnection $db DB Connection.
  * @param int $userId ID of user to credit for.
  * @param number $amount Real money amount that has been registered. Will be stored with multiplied by 100, in order to store float numbers as integers.
  * @param string $subject Subject id for premium statement. Usually ID of action which triggered the payment.
  * @throws Exception if either the amount is <= 0 or if no price option is available for the specified amount.
  */
 public static function createPaymentAndCreditPremium(WebSoccer $websoccer, DbConnection $db, $userId, $amount, $subject)
 {
     if ($amount <= 0) {
         throw new Exception('Illegal amount: ' . $amount);
     }
     $realAmount = $amount * 100;
     // create payment statement
     $db->queryInsert(array('user_id' => $userId, 'amount' => $realAmount, 'created_date' => $websoccer->getNowAsTimestamp()), $websoccer->getConfig('db_prefix') . '_premiumpayment');
     // get premium amount to credit
     $priceOptions = explode(',', $websoccer->getConfig('premium_price_options'));
     if (count($priceOptions)) {
         foreach ($priceOptions as $priceOption) {
             $optionParts = explode(':', $priceOption);
             $realMoney = trim($optionParts[0]);
             $realMoneyAmount = $realMoney * 100;
             $premiumMoney = trim($optionParts[1]);
             // credit amount and end here
             if ($realAmount == $realMoneyAmount) {
                 self::creditAmount($websoccer, $db, $userId, $premiumMoney, $subject);
                 return;
             }
         }
     }
     // if reached here, no price option has been found for this amount
     throw new Exception('No price option found for amount: ' . $amount);
 }
 /**
  * Creates a new action log for the specified user and deletes old ones.
  * If there is already a recent log for the same action, it will onl update the timestamp.
  * 
  * @param WebSoccer $websoccer Application context.
  * @param DbConnection $db DB connection.
  * @param int $userId ID of user.
  * @param string $actionId Action name.
  */
 public static function createOrUpdateActionLog(WebSoccer $websoccer, DbConnection $db, $userId, $actionId)
 {
     $fromTable = $websoccer->getConfig('db_prefix') . '_useractionlog';
     // delete old entries of user (entries which are older than 20 days)
     $deleteTimeThreshold = $websoccer->getNowAsTimestamp() - 24 * 3600 * 20;
     $db->queryDelete($fromTable, 'user_id = %d AND created_date < %d', array($userId, $deleteTimeThreshold));
     // check if action has been triggered within the last X minutes. If so, just update timestamp rather than filling DB unnecessary.
     $timeThreshold = $websoccer->getNowAsTimestamp() - 30 * 60;
     $result = $db->querySelect('id', $fromTable, 'user_id = %d AND action_id = \'%s\' AND created_date >= %d ORDER BY created_date DESC', array($userId, $actionId, $timeThreshold), 1);
     $lastLog = $result->fetch_array();
     $result->free();
     // update last log
     if ($lastLog) {
         $db->queryUpdate(array('created_date' => $websoccer->getNowAsTimestamp()), $fromTable, 'id = %d', $lastLog['id']);
         // create new log
     } else {
         $db->queryInsert(array('user_id' => $userId, 'action_id' => $actionId, 'created_date' => $websoccer->getNowAsTimestamp()), $fromTable);
     }
 }
 private static function createMatchForTeamAndRound(WebSoccer $websoccer, DbConnection $db, $teamId, $roundId, $firstRoundDate, $secondRoundDate, $cupName, $cupRound)
 {
     // get opponent team from pending list
     $pendingTable = $websoccer->getConfig('db_prefix') . '_cup_round_pending';
     $result = $db->querySelect('team_id', $pendingTable, 'cup_round_id = %d', $roundId, 1);
     $opponent = $result->fetch_array();
     $result->free();
     // no opponent -> add to pending list
     if (!$opponent) {
         $db->queryInsert(array('team_id' => $teamId, 'cup_round_id' => $roundId), $pendingTable);
     } else {
         $matchTable = $websoccer->getConfig('db_prefix') . '_spiel';
         $type = 'Pokalspiel';
         // determine home team of first round (choose randomly)
         if (SimulationHelper::selectItemFromProbabilities(array(1 => 50, 0 => 50))) {
             $homeTeam = $teamId;
             $guestTeam = $opponent['team_id'];
         } else {
             $homeTeam = $opponent['team_id'];
             $guestTeam = $teamId;
         }
         // create first round
         $db->queryInsert(array('spieltyp' => $type, 'pokalname' => $cupName, 'pokalrunde' => $cupRound, 'home_verein' => $homeTeam, 'gast_verein' => $guestTeam, 'datum' => $firstRoundDate), $matchTable);
         // create second round
         if ($secondRoundDate) {
             $db->queryInsert(array('spieltyp' => $type, 'pokalname' => $cupName, 'pokalrunde' => $cupRound, 'home_verein' => $guestTeam, 'gast_verein' => $homeTeam, 'datum' => $secondRoundDate), $matchTable);
         }
         // remove opponent team from pending list
         $db->queryDelete($pendingTable, 'team_id = %d AND cup_round_id = %d', array($opponent['team_id'], $roundId));
     }
 }
 private static function _transferPlayer(WebSoccer $websoccer, DbConnection $db, $playerId, $targetClubId, $targetUserId, $currentUserId, $currentClubId, $amount, $exchangePlayer1 = 0, $exchangePlayer2 = 0)
 {
     $db->queryUpdate(array("verein_id" => $targetClubId, "vertrag_spiele" => $websoccer->getConfig("transferoffers_contract_matches")), $websoccer->getConfig("db_prefix") . "_spieler", "id = %d", $playerId);
     // create log
     $db->queryInsert(array("bid_id" => 0, "datum" => $websoccer->getNowAsTimestamp(), "spieler_id" => $playerId, "seller_user_id" => $currentUserId, "seller_club_id" => $currentClubId, "buyer_user_id" => $targetUserId, "buyer_club_id" => $targetClubId, "directtransfer_amount" => $amount, "directtransfer_player1" => $exchangePlayer1, "directtransfer_player2" => $exchangePlayer2), $websoccer->getConfig("db_prefix") . "_transfer");
 }
 /**
  * Creates a new record within the simulation state DB table for the specified player.
  * The state table enables live-simulation (simulating not the whole match a once, but only parts) and also stores all
  * statistical information about the player for the specified match id (e.g. ball contacts, cards, attempts, etc.).
  * 
  * @param WebSoccer $websoccer application context.
  * @param DbConnection $db Database connection.
  * @param int $matchId match ID
  * @param SimulationPlayer $player player model to store.
  * @param boolean $onBench TRUE if player is on bench, FALSE if on pitch.
  */
 public static function createSimulationRecord(WebSoccer $websoccer, DbConnection $db, $matchId, SimulationPlayer $player, $onBench = FALSE)
 {
     $fromTable = $websoccer->getConfig('db_prefix') . '_spiel_berechnung';
     $db->queryInsert(self::getPlayerColumns($matchId, $player, $onBench ? 'Ersatzbank' : '1'), $fromTable);
 }
 /**
  * Creates a new item for a youth match report.
  * 
  * @param WebSoccer $websoccer Application context.
  * @param DbConnection $db DB connection.
  * @param int $matchId ID of match.
  * @param int $minute minute at which event happened.
  * @param string $messageKey Messages key.
  * @param string $messageData Values for placeholders within message.
  * @param boolean $isHomeTeamWithBall TRUE if Home team is the main affected team at this event.
  */
 public static function createMatchReportItem(WebSoccer $websoccer, DbConnection $db, $matchId, $minute, $messageKey, $messageData = null, $isHomeTeamWithBall = FALSE)
 {
     $messageDataStr = "";
     if (is_array($messageData)) {
         $messageDataStr = json_encode($messageData);
     }
     $columns = array("match_id" => $matchId, "minute" => $minute, "message_key" => $messageKey, "message_data" => $messageDataStr, "home_on_ball" => $isHomeTeamWithBall ? "1" : "0");
     $db->queryInsert($columns, $websoccer->getConfig("db_prefix") . "_youthmatch_reportitem");
 }