function OnLoadPageData()
 {
     /* @var $match_manager MatchManager */
     /* @var $editor TournamentEditControl */
     # get id of Match
     $i_id = $this->match_manager->GetItemId();
     if (!$i_id) {
         return;
     }
     # no need to read if redisplaying invalid form
     if ($this->IsValid()) {
         $this->match_manager->ReadByMatchId(array($i_id));
         $this->tournament = $this->match_manager->GetFirst();
         if ($this->tournament instanceof Match) {
             $this->b_user_is_match_owner = AuthenticationManager::GetUser()->GetId() == $this->tournament->GetAddedBy()->GetId();
             $this->b_is_tournament = $this->tournament->GetMatchType() == MatchType::TOURNAMENT;
         } else {
             return;
         }
     }
     if ($this->b_user_is_match_admin or $this->b_user_is_match_owner) {
         # Get all seasons
         # Don't filter by match type at this point because we want to know what other types of match the seasons support.
         # If it's tournaments only, they'll be treated differently.
         require_once 'stoolball/season-manager.class.php';
         $season_manager = new SeasonManager($this->GetSettings(), $this->GetDataConnection());
         $season_dates = Season::SeasonDates($this->tournament->GetStartTime());
         $season_manager->FilterByDateStart($season_dates[0]);
         $season_manager->FilterByDateEnd($season_dates[1]);
         $season_manager->ReadSeasonSummaries(array($this->tournament->GetPlayerType()));
         $this->editor->Seasons()->SetItems($season_manager->GetItems());
         unset($season_manager);
     }
 }
 function OnLoadPageData()
 {
     /* @var Match $tournament */
     # check parameter
     if (!isset($_GET['match']) or !is_numeric($_GET['match'])) {
         $this->Redirect();
     }
     # get tournament
     $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
     $match_manager->ReadByMatchId(array($_GET['match']));
     $this->tournament = $match_manager->GetFirst();
     unset($match_manager);
     # must have found a match
     if (!$this->tournament instanceof Match) {
         $this->page_not_found = true;
         return;
     }
     # Get some stats on the best players
     require_once 'stoolball/statistics/statistics-manager.class.php';
     $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
     $statistics_manager->FilterByTournament(array($this->tournament->GetId()));
     $this->statistics["querystring"] = "?tournament=" . $this->tournament->GetId();
     require_once "_summary-data-query.php";
     unset($statistics_manager);
 }
 function OnLoadPageData()
 {
     # get match
     if (!is_object($this->match)) {
         $i_id = $this->manager->GetItemId($this->match);
         if ($i_id) {
             $this->manager->ReadByMatchId(array($i_id));
             $this->match = $this->manager->GetFirst();
         }
     }
     # tidy up
     unset($this->manager);
     if (is_object($this->match) and $this->match->GetMatchType() == MatchType::TOURNAMENT) {
         $this->match_or_tournament = 'tournament';
     }
 }
 public function OnLoadPageData()
 {
     if (!is_null($this->i_match_id)) {
         require_once 'stoolball/match-manager.class.php';
         $o_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
         $o_manager->ReadByMatchId(array($this->i_match_id));
         $o_match = $o_manager->GetFirst();
         if ($o_match instanceof Match) {
             $this->s_cal_title = $o_match->GetTitle() . ' – ' . $o_match->GetStartTimeFormatted();
             $this->s_cal_url = $o_match->GetCalendarNavigateUrl();
         }
         unset($o_manager);
     } else {
         if (!is_null($this->i_team_id)) {
             require_once 'stoolball/team-manager.class.php';
             $o_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
             $o_manager->ReadById(array($this->i_team_id));
             $o_team = $o_manager->GetFirst();
             if ($o_team instanceof Team) {
                 $this->s_cal_title = $o_team->GetName() . '\'s current season';
                 $this->s_cal_url = $o_team->GetCalendarNavigateUrl();
             }
             unset($o_manager);
         } else {
             if (!is_null($this->i_season_id)) {
                 require_once 'stoolball/competition-manager.class.php';
                 $o_manager = new CompetitionManager($this->GetSettings(), $this->GetDataConnection());
                 $o_manager->ReadById(null, array($this->i_season_id));
                 $o_comp = $o_manager->GetFirst();
                 if ($o_comp instanceof Competition) {
                     $o_season = $o_comp->GetWorkingSeason();
                     $this->s_cal_title = $o_season->GetCompetitionName();
                     $this->s_cal_url = $o_season->GetCalendarNavigateUrl();
                 }
                 unset($o_manager);
             } else {
                 if ($this->tournament_player_type) {
                     $this->s_matches = $this->tournament_player_type . " tournaments";
                     $this->s_cal_url = "/tournaments/" . $this->tournament_player_type . "/calendar";
                 }
             }
         }
     }
     if (is_null($this->s_cal_url)) {
         header('Location: /play/');
         exit;
     }
 }
 function OnLoadPageData()
 {
     /* @var $match_manager MatchManager */
     /* @var $editor TournamentMatchesControl */
     # get id of Match
     $i_id = $this->match_manager->GetItemId();
     if (!$i_id) {
         return;
     }
     # no need to read if redisplaying invalid form
     if ($this->IsValid()) {
         $this->match_manager->ReadByMatchId(array($i_id));
         $this->tournament = $this->match_manager->GetFirst();
         if ($this->tournament instanceof Match) {
             $this->b_is_tournament = $this->tournament->GetMatchType() == MatchType::TOURNAMENT;
         } else {
             return;
         }
     }
 }
 function OnLoadPageData()
 {
     /* @var $match_manager MatchManager */
     /* @var $editor TournamentEditControl */
     # get id of Match
     $i_id = $this->match_manager->GetItemId();
     if (!$i_id) {
         return;
     }
     # no need to read if redisplaying invalid form
     if ($this->IsValid()) {
         $this->match_manager->ReadByMatchId(array($i_id));
         $this->tournament = $this->match_manager->GetFirst();
         if ($this->tournament instanceof Match) {
             $this->b_user_is_match_owner = AuthenticationManager::GetUser()->GetId() == $this->tournament->GetAddedBy()->GetId();
             $this->b_is_tournament = $this->tournament->GetMatchType() == MatchType::TOURNAMENT;
         } else {
             return;
         }
     }
     if ($this->b_user_is_match_admin or $this->b_user_is_match_owner) {
         # get all grounds
         require_once 'stoolball/ground-manager.class.php';
         $o_ground_manager = new GroundManager($this->GetSettings(), $this->GetDataConnection());
         $o_ground_manager->ReadAll();
         $this->editor->Grounds()->SetItems($o_ground_manager->GetItems());
         unset($o_ground_manager);
         # get teams in seasons, in order to promote home grounds of teams
         $season_ids = array();
         foreach ($this->tournament->Seasons() as $season) {
             $season_ids[] = $season->GetId();
         }
         require_once 'stoolball/team-manager.class.php';
         $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
         if (count($season_ids)) {
             $team_manager->ReadBySeasonId($season_ids);
             $this->editor->ProbableTeams()->SetItems($team_manager->GetItems());
         }
         unset($team_manager);
     }
 }
 function OnLoadPageData()
 {
     /* @var Match $tournament */
     # check parameter
     if (!isset($_GET['match']) or !is_numeric($_GET['match'])) {
         $this->Redirect();
     }
     # get match
     $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
     $match_manager->ReadByMatchId(array($_GET['match']));
     $match_manager->ExpandMatchScorecards();
     $this->match = $match_manager->GetFirst();
     unset($match_manager);
     # must have found a match
     if (!$this->match instanceof Match) {
         $this->page_not_found = true;
         return;
     }
     $result = $this->match->Result();
     $this->has_statistics = $result->HomeOvers()->GetCount() or $result->AwayOvers()->GetCount();
 }
 function OnLoadPageData()
 {
     /* @var $match_manager MatchManager */
     # get id of Match
     $i_id = $this->match_manager->GetItemId();
     # Get details of match but, if invalid, don't replace submitted details with saved ones
     if ($i_id and $this->IsValid()) {
         $this->match_manager->ReadByMatchId(array($i_id));
         $this->match_manager->ExpandMatchScorecards();
         $this->match = $this->match_manager->GetFirst();
         if ($this->match instanceof Match) {
             $this->b_user_is_match_owner = AuthenticationManager::GetUser()->GetId() == $this->match->GetAddedBy()->GetId();
             $this->b_is_tournament = $this->match->GetMatchType() == MatchType::TOURNAMENT;
         }
     }
     unset($this->match_manager);
     # Tournament or match in the future or not played is page not found
     $editable_results = array(MatchResult::UNKNOWN, MatchResult::HOME_WIN, MatchResult::AWAY_WIN, MatchResult::TIE, MatchResult::ABANDONED);
     if (!$this->match instanceof Match or $this->b_is_tournament or $this->match->GetStartTime() > gmdate('U') or !in_array($this->match->Result()->GetResultType(), $editable_results)) {
         http_response_code(404);
         $this->page_not_found = true;
     }
 }
 /**
  * If the tournament parameter is in the query string apply tournament filter
  * @param SiteSettings $settings
  * @param MySqlConnection $connection
  * @param StatisticsManager $statistics_manager
  */
 public static function ApplyTournamentFilter(SiteSettings $settings, MySqlConnection $connection, StatisticsManager $statistics_manager)
 {
     $filter = "";
     if (isset($_GET['tournament']) and is_numeric($_GET['tournament'])) {
         require_once 'stoolball/match-manager.class.php';
         $match_manager = new MatchManager($settings, $connection);
         $match_manager->ReadByMatchId(array($_GET['tournament']));
         $tournament = $match_manager->GetFirst();
         unset($match_manager);
         if (!is_null($tournament)) {
             $statistics_manager->FilterByTournament(array($tournament->GetId()));
             $filter = "in the " . $tournament->GetTitle() . " on " . Date::BritishDate($tournament->GetStartTime()) . " ";
         }
     }
     return $filter;
 }
 function OnLoadPageData()
 {
     /* @var $match_manager MatchManager */
     /* @var $editor MatchEditControl */
     # get id of Match
     $i_id = $this->match_manager->GetItemId();
     if ($i_id) {
         # Get details of match but, if invalid, don't replace submitted details with saved ones
         if ($this->IsValid()) {
             $this->match_manager->ReadByMatchId(array($i_id));
             $this->match_manager->ExpandMatchScorecards();
             $this->match = $this->match_manager->GetFirst();
             if ($this->match instanceof Match) {
                 $this->b_user_is_match_owner = AuthenticationManager::GetUser()->GetId() == $this->match->GetAddedBy()->GetId();
                 $this->b_is_tournament = $this->match->GetMatchType() == MatchType::TOURNAMENT;
             }
         }
         unset($this->match_manager);
         # get all competitions if user has permission to change the season
         if ($this->b_user_is_match_admin) {
             require_once 'stoolball/competition-manager.class.php';
             $o_comp_manager = new CompetitionManager($this->GetSettings(), $this->GetDataConnection());
             $o_comp_manager->ReadAllSummaries();
             $this->editor->SetSeasons(CompetitionManager::GetSeasonsFromCompetitions($o_comp_manager->GetItems()));
             unset($o_comp_manager);
         }
         if ($this->b_user_is_match_admin or $this->b_user_is_match_owner) {
             # get all teams
             $season_ids = array();
             if ($this->match instanceof Match) {
                 foreach ($this->match->Seasons() as $season) {
                     $season_ids[] = $season->GetId();
                 }
             }
             require_once 'stoolball/team-manager.class.php';
             $o_team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
             if ($this->match instanceof Match and $this->match->GetMatchType() == MatchType::TOURNAMENT_MATCH) {
                 $o_team_manager->FilterByTournament(array($this->match->GetTournament()->GetId()));
                 $o_team_manager->FilterByTeamType(array());
                 # override default to allow all team types
                 $o_team_manager->ReadTeamSummaries();
             } else {
                 if ($this->b_user_is_match_admin or !count($season_ids) or $this->match->GetMatchType() == MatchType::FRIENDLY) {
                     $o_team_manager->ReadById();
                     # we need full data on the teams to get the seasons they are playing in;
                 } else {
                     # If the user can't change the season, why let them select a team that's not in the season?
                     $o_team_manager->ReadBySeasonId($season_ids);
                 }
             }
             $this->editor->SetTeams(array($o_team_manager->GetItems()));
             unset($o_team_manager);
             # get all grounds
             require_once 'stoolball/ground-manager.class.php';
             $o_ground_manager = new GroundManager($this->GetSettings(), $this->GetDataConnection());
             $o_ground_manager->ReadAll();
             $this->editor->SetGrounds($o_ground_manager->GetItems());
             unset($o_ground_manager);
         }
     }
     # Tournament or match not found is page not found
     if (!$this->match instanceof Match or $this->b_is_tournament) {
         http_response_code(404);
         $this->page_not_found = true;
     }
 }
 function OnLoadPageData()
 {
     /* @var $o_last_match Match */
     /* @var $season Season */
     /* @var $team Team */
     # First best guess at where user came from is the page field posted back,
     # second best is tournaments page. Either can be tampered with, so there will be
     # a check later before they're used for redirection. If there's a context
     # season or team its URL will be read from the db and overwrite this later.
     if (isset($_POST['page'])) {
         $this->destination_url_if_cancelled = $_POST['page'];
     } else {
         $this->destination_url_if_cancelled = "/tournaments";
     }
     # new data manager
     $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
     $match_manager->FilterByMatchType(array(MatchType::TOURNAMENT));
     # Check whether cancel was clicked
     if ($this->IsPostback() and $this->editor->CancelClicked()) {
         # new tournament, nothing saved yet, so just send user back where they came from
         $this->Cancel();
     }
     # Save match
     if ($this->IsPostback() and $this->IsValid()) {
         # Get posted match
         $this->tournament = $this->editor->GetDataObject();
         # Save match
         $match_manager->SaveFixture($this->tournament);
         if (count($this->tournament->GetAwayTeams())) {
             $match_manager->SaveTeams($this->tournament);
         }
         if ($this->season instanceof Season) {
             $this->tournament->Seasons()->Add($this->season);
             $match_manager->SaveSeasons($this->tournament, true);
         }
         http_response_code(303);
         $this->Redirect($this->tournament->AddTournamentTeamsUrl());
     }
     if (isset($this->season)) {
         $season_manager = new SeasonManager($this->GetSettings(), $this->GetDataConnection());
         $season_manager->ReadById(array($this->season->GetId()));
         $this->season = $season_manager->GetFirst();
         $this->editor->SetContextSeason($this->season);
         $this->destination_url_if_cancelled = $this->season->GetNavigateUrl();
         unset($season_manager);
         # If we're adding a match to a season, get last game in season for its date
         $match_manager->ReadLastInSeason($this->season->GetId());
     }
     if (isset($this->team)) {
         # Get more information about the team itself
         require_once 'stoolball/team-manager.class.php';
         $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
         $team_manager->ReadById(array($this->team->GetId()));
         $this->team = $team_manager->GetFirst();
         $this->editor->SetContextTeam($this->team);
         $this->destination_url_if_cancelled = $this->team->GetNavigateUrl();
         # Get the last game already scheduled for the team to use its date
         $match_manager->ReadLastForTeam($this->team->GetId());
         # Read teams played in the last year in order to get their grounds, which will be put at the top of the select list
         $team_manager->ReadRecentOpponents(array($this->team->GetId()), 12);
         $this->editor->ProbableTeams()->SetItems($team_manager->GetItems());
         unset($team_manager);
     }
     # Use the date of the most recent tournament if it was this year, otherwise just use the default of today
     $o_last_match = $match_manager->GetFirst();
     if (is_object($o_last_match) and gmdate('Y', $o_last_match->GetStartTime()) == gmdate('Y')) {
         if ($o_last_match->GetIsStartTimeKnown()) {
             # If the last match has a time, use it
             $this->editor->SetDefaultTime($o_last_match->GetStartTime());
         } else {
             # If the last match has no time, use 11am BST
             $this->editor->SetDefaultTime(gmmktime(10, 0, 0, gmdate('m', $o_last_match->GetStartTime()), gmdate('d', $o_last_match->GetStartTime()), gmdate('Y', $o_last_match->GetStartTime())));
         }
     }
     unset($match_manager);
     # Get grounds
     $o_ground_manager = new GroundManager($this->GetSettings(), $this->GetDataConnection());
     $o_ground_manager->ReadAll();
     $a_grounds = $o_ground_manager->GetItems();
     $this->editor->Grounds()->SetItems($a_grounds);
     unset($o_ground_manager);
 }
    public function OnLoadPageData()
    {
        $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
        $match_manager->ReadByMatchId(array($_GET['match']));
        $match_manager->ExpandMatchScorecards();
        $this->match = $match_manager->GetFirst();
        unset($match_manager);
        if ($this->match->GetHomeTeam() instanceof Team and $this->match->GetAwayTeam() instanceof Team) {
            ?>
{
    "worm": {
        "labels": [
            <?php 
            $overs = $this->HowManyOversInTheMatch();
            echo $this->BuildOversLabels(0, $overs);
            ?>
        
        ],
        "datasets": [
        <?php 
            $home_batted_first = $this->match->Result()->GetHomeBattedFirst();
            if ($home_batted_first === true || is_null($home_batted_first)) {
                ?>
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetHomeTeam()->GetName(), $home_batted_first === true);
                ?>
",
                "data": [0<?php 
                echo $this->BuildCumulativeOverTotals($this->match->Result()->AwayOvers()->GetItems());
                ?>
]
            },
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetAwayTeam()->GetName(), $home_batted_first === false);
                ?>
",
                "data": [0<?php 
                echo $this->BuildCumulativeOverTotals($this->match->Result()->HomeOvers()->GetItems());
                ?>
]
            }      
            <?php 
            } else {
                ?>
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetAwayTeam()->GetName(), $home_batted_first === false);
                ?>
",
                "data": [0<?php 
                echo $this->BuildCumulativeOverTotals($this->match->Result()->HomeOvers()->GetItems());
                ?>
]
            },      
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetHomeTeam()->GetName(), $home_batted_first === true);
                ?>
",
                "data": [0<?php 
                echo $this->BuildCumulativeOverTotals($this->match->Result()->AwayOvers()->GetItems());
                ?>
]
            }
            <?php 
            }
            ?>
]    
    },
    "runRate": {
        "labels": [
            <?php 
            echo $this->BuildOversLabels(0, $overs);
            ?>
        
        ],
        "datasets": [
        <?php 
            $home_batted_first = $this->match->Result()->GetHomeBattedFirst();
            if ($home_batted_first === true || is_null($home_batted_first)) {
                ?>
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetHomeTeam()->GetName() . " run rate", $home_batted_first === true);
                ?>
",
                "data": [0<?php 
                echo $this->BuildCumulativeRunRate($this->match->Result()->AwayOvers()->GetItems());
                ?>
]
            },
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetAwayTeam()->GetName() . " run rate", null);
                ?>
",
                "data": [0<?php 
                echo $this->BuildCumulativeRunRate($this->match->Result()->HomeOvers()->GetItems());
                ?>
]
            },
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetAwayTeam()->GetName() . " rate required", null);
                ?>
",
                "data": [<?php 
                echo $this->BuildRunRateRequired($this->match->Result()->AwayOvers()->GetItems(), $this->match->Result()->HomeOvers()->GetItems(), $overs);
                ?>
]
            }      
            <?php 
            } else {
                ?>
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetAwayTeam()->GetName() . " run rate", $home_batted_first === false);
                ?>
",
                "data": [0<?php 
                echo $this->BuildCumulativeRunRate($this->match->Result()->HomeOvers()->GetItems());
                ?>
]
            },      
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetHomeTeam()->GetName() . " run rate", null);
                ?>
",
                "data": [0<?php 
                echo $this->BuildCumulativeRunRate($this->match->Result()->AwayOvers()->GetItems());
                ?>
]
            },      
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetHomeTeam()->GetName() . " rate required", null);
                ?>
",
                "data": [<?php 
                echo $this->BuildRunRateRequired($this->match->Result()->HomeOvers()->GetItems(), $this->match->Result()->AwayOvers()->GetItems(), $overs);
                ?>
]
            }
            <?php 
            }
            ?>
]    
    },
    "manhattanFirstInnings": {
        "labels": [
            <?php 
            $overs = $this->HowManyOversInTheMatch();
            echo $this->BuildOversLabels(1, $overs);
            ?>
        
        ],
        "datasets": [
        <?php 
            if ($home_batted_first === true || is_null($home_batted_first)) {
                ?>
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetHomeTeam()->GetName(), $home_batted_first === true);
                ?>
",
                "data": [<?php 
                echo $this->BuildOverTotals($this->match->Result()->AwayOvers()->GetItems(), $overs);
                ?>
]
            }      
            <?php 
            } else {
                ?>
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetAwayTeam()->GetName(), $home_batted_first === false);
                ?>
",
                "data": [<?php 
                echo $this->BuildOverTotals($this->match->Result()->HomeOvers()->GetItems(), $overs);
                ?>
]
            }      
        <?php 
            }
            ?>
        ]
    },
    "manhattanSecondInnings": {
        "labels": [
            <?php 
            $overs = $this->HowManyOversInTheMatch();
            echo $this->BuildOversLabels(1, $overs);
            ?>
        
        ],
        "datasets": [
        <?php 
            if ($home_batted_first === false) {
                ?>
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetHomeTeam()->GetName(), $home_batted_first === true);
                ?>
",
                "data": [<?php 
                echo $this->BuildOverTotals($this->match->Result()->AwayOvers()->GetItems(), $overs);
                ?>
]
            }      
            <?php 
            } else {
                ?>
            {
                "label": "<?php 
                echo $this->BuildTeamNameLabel($this->match->GetAwayTeam()->GetName(), $home_batted_first === false);
                ?>
",
                "data": [<?php 
                echo $this->BuildOverTotals($this->match->Result()->HomeOvers()->GetItems(), $overs);
                ?>
]
            }      
        <?php 
            }
            ?>
        ]
    }
    <?php 
        }
        ?>
}
        <?php 
        exit;
    }
 /**
  * Call this method when a match has changed to update derived match data 
  */
 public function UpdateMatchDataInStatistics(MatchManager $match_manager, $match_id)
 {
     $match_manager->ReadByMatchId(array($match_id));
     $match = $match_manager->GetFirst();
     $sql = "UPDATE nsa_player_match SET \r\n                           match_title = " . Sql::ProtectString($this->GetDataConnection(), $match->GetTitle()) . ",\r\n                           won_match = NULL \r\n                           WHERE match_id = " . Sql::ProtectNumeric($match->GetId());
     $this->GetDataConnection()->query($sql);
     $match_result = $match->Result()->GetResultType();
     if ($match_result == MatchResult::HOME_WIN) {
         $sql = "UPDATE nsa_player_match \r\n                           SET won_match = 1 \r\n                           WHERE match_id = " . Sql::ProtectNumeric($match->GetId()) . "\r\n                           AND team_id = " . Sql::ProtectNumeric($match->GetHomeTeamId());
         $this->GetDataConnection()->query($sql);
         $sql = "UPDATE nsa_player_match \r\n                           SET won_match = -1 \r\n                           WHERE match_id = " . Sql::ProtectNumeric($match->GetId()) . "\r\n                           AND team_id = " . Sql::ProtectNumeric($match->GetAwayTeamId());
         $this->GetDataConnection()->query($sql);
     } else {
         if ($match_result == MatchResult::AWAY_WIN) {
             $sql = "UPDATE nsa_player_match \r\n                           SET won_match = 1 \r\n                           WHERE match_id = " . Sql::ProtectNumeric($match->GetId()) . "\r\n                           AND team_id = " . Sql::ProtectNumeric($match->GetAwayTeamId());
             $this->GetDataConnection()->query($sql);
             $sql = "UPDATE nsa_player_match \r\n                           SET won_match = -1 \r\n                           WHERE match_id = " . Sql::ProtectNumeric($match->GetId()) . "\r\n                           AND team_id = " . Sql::ProtectNumeric($match->GetHomeTeamId());
             $this->GetDataConnection()->query($sql);
         } else {
             if ($match_result == MatchResult::TIE) {
                 $sql = "UPDATE nsa_player_match \r\n                           SET won_match = 0 \r\n                           WHERE match_id = " . Sql::ProtectNumeric($match->GetId());
                 $this->GetDataConnection()->query($sql);
             }
         }
     }
 }
 function OnLoadPageData()
 {
     /* @var $o_last_match Match */
     /* @var $season Season */
     /* @var $team Team */
     # new data manager
     $o_match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
     # Collect season to add this match to, starting with the URL
     # get season and teams (was at this stage because editor needed teams to build its
     # posted data object, but that's no longer the case so probably could be later if needed)
     if (isset($this->i_season_id)) {
         $season_manager = new SeasonManager($this->GetSettings(), $this->GetDataConnection());
         $season_manager->ReadById(array($this->i_season_id));
         $this->season = $season_manager->GetFirst();
         unset($season_manager);
         $this->edit->Seasons()->Add($this->season);
         # If there are at least 2 teams in the season, show only those teams, otherwise show all teams of the relevant player type
         if (count($this->season->GetTeams()) > 1) {
             $this->edit->SetTeams(array($this->season->GetTeams()));
         } else {
             require_once 'stoolball/team-manager.class.php';
             $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
             $team_manager->FilterByPlayerType(array($this->season->GetCompetition()->GetPlayerType()));
             $team_manager->ReadTeamSummaries();
             $this->edit->SetTeams(array($team_manager->GetItems()));
             unset($team_manager);
         }
     }
     # Not elseif, because when you've added a match there's a season, but we still need this to run to populate
     # the choices for the next match to be added
     if ($this->team instanceof Team) {
         # Otherwise it should be a team.
         # Get more information about the team itself
         require_once 'stoolball/team-manager.class.php';
         $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
         $team_manager->ReadById(array($this->team->GetId()));
         $this->team = $team_manager->GetFirst();
         if (!is_null($this->team)) {
             $this->edit->SetContextTeam($this->team);
             $season_ids = array();
             $team_groups = array();
             $a_exclude_team_ids = array();
             $team_manager->FilterByActive(true);
             # Add the home team first
             $team_groups[] = array($this->team);
             $a_exclude_team_ids[] = $this->team->GetId();
             # Get the seasons this team is in...
             $season_manager = new SeasonManager($this->GetSettings(), $this->GetDataConnection());
             if ($this->i_match_type == MatchType::FRIENDLY) {
                 # For a friendly, any group of teams they play with is fine
                 $season_manager->ReadCurrentSeasonsByTeamId(array($this->team->GetId()));
             } else {
                 # For anything else, get the seasons *for this type of match*
                 $season_manager->ReadCurrentSeasonsByTeamId(array($this->team->GetId()), array($this->i_match_type));
             }
             $seasons = $season_manager->GetItems();
             unset($season_manager);
             $this->edit->Seasons()->Clear();
             # on postback, the season just added is already there, so clear to prevent a duplicate
             foreach ($seasons as $season) {
                 $this->edit->Seasons()->Add($season);
                 $season_ids[] = $season->GetId();
             }
             #... and their opponent teams in those seasons
             if (count($season_ids)) {
                 $team_manager->FilterExceptTeams($a_exclude_team_ids);
                 $team_manager->ReadBySeasonId($season_ids);
                 $season_teams = $team_manager->GetItems();
                 if (count($season_teams)) {
                     $team_groups['This season\'s teams'] = $season_teams;
                 }
                 foreach ($season_teams as $team) {
                     $a_exclude_team_ids[] = $team->GetId();
                 }
             }
             # ...and if this is a friendly it could be any other team
             if ($this->i_match_type == MatchType::FRIENDLY) {
                 # get any other teams they played in the last 2 years, and combine with existing results
                 $team_manager->FilterExceptTeams($a_exclude_team_ids);
                 $team_manager->ReadRecentOpponents(array($this->team->GetId()), 24);
                 $recent_opponents = $team_manager->GetItems();
                 if (count($recent_opponents)) {
                     $team_groups['Recent opponents'] = $recent_opponents;
                 }
                 foreach ($recent_opponents as $team) {
                     $a_exclude_team_ids[] = $team->GetId();
                 }
                 # get any other teams they might play, and combine with existing results
                 $team_manager->FilterExceptTeams($a_exclude_team_ids);
                 $team_manager->ReadAll();
                 $team_groups['Other teams'] = $team_manager->GetItems();
             }
             # What if there are still no opponents to choose from? In that case select all teams.
             if (count($team_groups) == 1) {
                 $team_manager->FilterExceptTeams($a_exclude_team_ids);
                 $team_manager->ReadAll();
                 $team_groups[] = $team_manager->GetItems();
             }
             # Offer those teams to select from
             if ($total_groups = count($team_groups)) {
                 # If only two groups (home team + 1 group), don't group teams. Remove the only key from the array.
                 if ($total_groups == 2) {
                     $keys = array_keys($team_groups);
                     $team_groups = array($team_groups[$keys[0]], $team_groups[$keys[1]]);
                 }
                 $this->edit->SetTeams($team_groups);
             }
         }
         unset($team_manager);
     }
     # Save match
     if ($this->IsPostback() and $this->IsValid()) {
         # Get posted match
         $this->match = $this->edit->GetDataObject();
         if (!$this->IsRefresh()) {
             # Save match
             $o_match_manager->SaveFixture($this->match);
             $o_match_manager->SaveSeasons($this->match, true);
             $o_match_manager->NotifyMatchModerator($this->match->GetId());
             # Update 'next 5 matches'
             $o_match_manager->ReadNext();
             $this->a_next_matches = $o_match_manager->GetItems();
         }
         # Reset control for new match
         $this->edit->SetDataObject(new Match($this->GetSettings()));
     }
     $o_match_manager->FilterByMatchType(array($this->i_match_type));
     if (isset($this->i_season_id)) {
         # If we're adding a match to a season, get last game in season for its date
         $o_match_manager->ReadLastInSeason($this->season->GetId());
     } else {
         if ($this->team instanceof Team) {
             # Get the last game already scheduled for the team to use its date
             $o_match_manager->ReadLastForTeam($this->team->GetId());
         }
     }
     $o_last_match = $o_match_manager->GetFirst();
     if (is_object($o_last_match)) {
         $current_season = Season::SeasonDates();
         if (gmdate('Y', $o_last_match->GetStartTime()) < gmdate('Y', $current_season[0])) {
             # If the last match this team played was last season, use the time but not the date
             $this->edit->SetDefaultTime(gmmktime(gmdate('H', $o_last_match->GetStartTime()), gmdate('i', $o_last_match->GetStartTime()), 0, gmdate('m'), gmdate('d'), gmdate('Y')));
         } else {
             # If the last match was this season and has a time, use it
             if ($o_last_match->GetIsStartTimeKnown()) {
                 $this->edit->SetDefaultTime($o_last_match->GetStartTime());
             } else {
                 # If the last match has no time, use 6.30pm BST
                 $this->edit->SetDefaultTime(gmmktime(17, 30, 0, gmdate('m', $o_last_match->GetStartTime()), gmdate('d', $o_last_match->GetStartTime()), gmdate('Y', $o_last_match->GetStartTime())));
             }
         }
     }
     unset($o_match_manager);
     # Get grounds
     $o_ground_manager = new GroundManager($this->GetSettings(), $this->GetDataConnection());
     $o_ground_manager->ReadAll();
     $a_grounds = $o_ground_manager->GetItems();
     $this->edit->SetGrounds($a_grounds);
     unset($o_ground_manager);
 }
 public function OnLoadPageData()
 {
     /* @var $topic ForumTopic */
     /* @var $match Match */
     # new data manager
     $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
     # get match
     $match_manager->ReadByMatchId(array($_GET['item']));
     $match_manager->ExpandMatchScorecards();
     $this->match = $match_manager->GetFirst();
     # must have found a match
     if (!$this->match instanceof Match) {
         header('Location: /matches/');
         exit;
     }
     # Update search engine
     if ($this->match->GetSearchUpdateRequired()) {
         require_once "search/match-search-adapter.class.php";
         $this->SearchIndexer()->DeleteFromIndexById("match" . $this->match->GetId());
         $adapter = new MatchSearchAdapter($this->match);
         $this->SearchIndexer()->Index($adapter->GetSearchableItem());
         $this->SearchIndexer()->CommitChanges();
         $match_manager->SearchUpdated($this->match->GetId());
     }
     # tidy up
     unset($match_manager);
     # Get comments
     $this->review_item = new ReviewItem($this->GetSettings());
     $this->review_item->SetId($this->match->GetId());
     $this->review_item->SetType(ContentType::STOOLBALL_MATCH);
     $this->review_item->SetTitle($this->match->GetTitle());
     $this->review_item->SetNavigateUrl("https://" . $this->GetSettings()->GetDomain() . $this->review_item->GetNavigateUrl());
     $this->review_item->SetLinkedDataUri($this->match->GetLinkedDataUri());
     $topic_manager = new TopicManager($this->GetSettings(), $this->GetDataConnection());
     if ($this->IsPostback()) {
         $this->SavePostedComments($topic_manager);
     }
     $topic_manager->ReadCommentsForReviewItem($this->review_item);
     $this->topic = $topic_manager->GetFirst();
     unset($topic_manager);
     if ($this->match->GetMatchType() == MatchType::TOURNAMENT or $this->match->GetMatchType() == MatchType::TOURNAMENT_MATCH) {
         # Get stats highlights
         require_once 'stoolball/statistics/statistics-manager.class.php';
         $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
         if ($this->match->GetMatchType() == MatchType::TOURNAMENT) {
             $statistics_manager->FilterByTournament(array($this->match->GetId()));
         } else {
             $statistics_manager->FilterByTournament(array($this->match->GetTournament()->GetId()));
         }
         $statistics_manager->FilterMaxResults(1);
         $this->best_batting = $statistics_manager->ReadBestBattingPerformance();
         $this->best_bowling = $statistics_manager->ReadBestBowlingPerformance();
         $this->most_runs = $statistics_manager->ReadBestPlayerAggregate("runs_scored");
         $this->most_wickets = $statistics_manager->ReadBestPlayerAggregate("wickets");
         $this->most_catches = $statistics_manager->ReadBestPlayerAggregate("catches");
         # See what stats we've got available
         $best_batting_count = count($this->best_batting);
         $best_bowling_count = count($this->best_bowling);
         $best_batters = count($this->most_runs);
         $best_bowlers = count($this->most_wickets);
         $best_catchers = count($this->most_catches);
         $this->has_player_stats = ($best_batting_count or $best_batters or $best_bowling_count or $best_bowlers or $best_catchers);
         if (!$this->has_player_stats) {
             $player_of_match = $statistics_manager->ReadBestPlayerAggregate("player_of_match");
             $this->has_player_stats = (bool) count($player_of_match);
         }
         unset($statistics_manager);
     }
 }
 function OnLoadPageData()
 {
     /* @var $o_match Match */
     /* @var $o_team Team */
     # new data manager
     $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
     # create repeater control, and save any posted data
     $this->repeater = new DataEditRepeater($this, 'CreateEditControl');
     $this->repeater->SetCssClass('matchResults');
     $this->repeater->SetPersistedParameters(array('team', 'season', "tournament"));
     $this->repeater->SetButtonText('Save all results');
     $this->repeater->SetShowButtonsAtTop(true);
     if ($this->IsPostback() and !$this->IsRefresh() and $this->IsValid()) {
         require_once 'forums/topic-manager.class.php';
         require_once 'forums/review-item.class.php';
         require_once 'forums/subscription-manager.class.php';
         $topic_manager = new TopicManager($this->GetSettings(), $this->GetDataConnection());
         foreach ($this->repeater->GetDataObjects() as $o_current_match) {
             /* @var $o_current_match Match */
             $match_manager->SaveResult($o_current_match);
             $match_manager->ExpandMatchUrl($o_current_match);
             $match_manager->NotifyMatchModerator($o_current_match->GetId());
             if (trim($o_current_match->GetNewComment())) {
                 $item_to_comment_on = new ReviewItem($this->GetSettings());
                 $item_to_comment_on->SetType(ContentType::STOOLBALL_MATCH);
                 $item_to_comment_on->SetId($o_current_match->GetId());
                 $item_to_comment_on->SetNavigateUrl("https://" . $this->GetSettings()->GetDomain() . $o_current_match->GetNavigateUrl());
                 $message = $topic_manager->SaveComment($item_to_comment_on, $o_current_match->GetNewComment());
                 # send subscription emails - new object each time to reset list of who's already recieved an email
                 $subs_manager = new SubscriptionManager($this->GetSettings(), $this->GetDataConnection());
                 $subs_manager->SendCommentsSubscriptions($item_to_comment_on, $message);
                 unset($subs_manager);
             }
         }
         $this->b_saved = true;
     }
     # get matches
     if (!is_null($this->i_team_id)) {
         $a_season_times = Season::SeasonDates();
         $match_manager->FilterByTeam(array($this->i_team_id));
         $match_manager->FilterByDateStart($a_season_times[0]);
         $match_manager->FilterByDateEnd($a_season_times[1]);
         $match_manager->ReadMatchSummaries();
     } else {
         if (!is_null($this->i_season_id)) {
             $match_manager->ReadBySeasonId(array($this->i_season_id), true);
         } else {
             if (!is_null($this->tournament_id)) {
                 $match_manager->FilterByTournament($this->tournament_id);
                 $this->a_matches = $match_manager->ReadMatchSummaries();
             }
         }
     }
     $this->a_matches = $match_manager->GetItems();
     # Make sure we have some matches
     if (count($this->a_matches)) {
         # If it's matches for a team, get the team
         if (!is_null($this->i_team_id)) {
             # Should only need to look at the first match, because the team must be a
             # part of that match in order for the match to be in this list
             $o_match =& $this->a_matches[0];
             $o_team = $o_match->GetHomeTeam();
             if ($o_team instanceof Team and $o_team->GetId() == $this->i_team_id) {
                 $this->team = $o_team;
             } else {
                 foreach ($o_match->GetAwayTeams() as $o_team) {
                     if ($o_team->GetId() == $this->i_team_id) {
                         $this->team = $o_team;
                         break;
                     }
                 }
             }
             if (!is_object($this->team)) {
                 $this->Redirect();
             }
             # Now that we have short URL data, if data has just been saved for team, redirect back to team
             if ($this->b_saved) {
                 $this->Redirect($this->team->GetNavigateUrl());
             }
         } else {
             if (!is_null($this->i_season_id)) {
                 # get details of the season
                 require_once 'stoolball/competition-manager.class.php';
                 $o_comp_manager = new CompetitionManager($this->GetSettings(), $this->GetDataConnection());
                 $o_comp_manager->ReadById(null, array($this->i_season_id));
                 $o_competition = $o_comp_manager->GetFirst();
                 unset($o_comp_manager);
                 if ($o_competition instanceof Competition) {
                     $this->season = $o_competition->GetWorkingSeason();
                 }
                 if (!$this->season instanceof Season) {
                     $this->Redirect();
                 }
                 # Now that we have short URL data, if data has just been saved for season, redirect back to season
                 if ($this->b_saved) {
                     $this->Redirect($this->season->GetNavigateUrl());
                 }
             } else {
                 if (!is_null($this->tournament_id)) {
                     $match_manager->ReadByMatchId(array($this->tournament_id));
                     $this->tournament = $match_manager->GetFirst();
                     if (!is_null($this->tournament)) {
                         # If the tournament has just been saved, now we have its URL so redirect to the thanks page
                         if ($this->b_saved) {
                             $this->Redirect($this->tournament->GetNavigateUrl());
                         }
                     }
                 }
             }
         }
     } else {
         $this->Redirect();
     }
     unset($match_manager);
 }