function OnLoadPageData()
 {
     # get item to be deleted
     if (!is_object($this->data_object)) {
         $id = $this->manager->GetItemId($this->data_object);
         $this->manager->ReadById(array($id));
         $this->data_object = $this->manager->GetFirst();
     }
     # tidy up
     unset($this->manager);
 }
 /**
  * (non-PHPdoc)
  * @see data/validation/DataValidator#Test($s_input, $a_keys)
  */
 public function Test($a_data, $a_keys)
 {
     /* Only way to be sure of testing name against what it will be matched against is to use the code that transforms it when saving */
     $team = new Team($this->GetSiteSettings());
     $team->SetName($a_data[$a_keys[1]]);
     $team->SetPlayerType($a_data[$a_keys[2]]);
     $team_manager = new TeamManager($this->GetSiteSettings(), $this->GetDataConnection());
     $team = $team_manager->MatchExistingTeam($team);
     unset($team_manager);
     $current_id = isset($a_data[$a_keys[0]]) ? $a_data[$a_keys[0]] : null;
     return !$team->GetId() or $team->GetId() == $current_id;
 }
 function OnLoadPageData()
 {
     require_once "stoolball/team-manager.class.php";
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     $team_manager->FilterByActive(true);
     $team_manager->ReadById();
     $this->teams = $team_manager->GetItems();
     require_once "stoolball/competition-manager.class.php";
     $comp_manager = new CompetitionManager($this->GetSettings(), $this->GetDataConnection());
     $comp_manager->SetExcludeInactive(true);
     $comp_manager->ReadById();
     $this->competitions = $comp_manager->GetItems();
 }
 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;
     }
 }
 private function ReadTeamData(array $team_ids)
 {
     if (!count($team_ids)) {
         return array();
     }
     require_once 'stoolball/team-manager.class.php';
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     $team_manager->ReadById($team_ids);
     $teams = $team_manager->GetItems();
     unset($team_manager);
     $team_ids = array();
     foreach ($teams as $team) {
         $team_ids[] = $team->GetId();
     }
     return array_combine($team_ids, $teams);
 }
 function OnLoadPageData()
 {
     /* @var Team $team */
     # check parameter
     if (!isset($_GET['item']) or !is_numeric($_GET['item'])) {
         $this->Redirect();
     }
     # get team
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     $team_manager->FilterByTeamType(array());
     $team_manager->ReadById(array($_GET['item']));
     $this->team = $team_manager->GetFirst();
     unset($team_manager);
     # must have found a team
     if (!$this->team instanceof Team) {
         $this->Redirect('/teams/');
     }
     # get match stats
     require_once 'stoolball/statistics/statistics-manager.class.php';
     $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
     $statistics_manager->FilterByTeam(array($this->team->GetId()));
     $statistics_manager->ReadMatchStatistics();
     $this->stats = $statistics_manager->GetItems();
     # Get some stats on the best players
     $this->statistics_query = "?team=" . $this->team->GetId();
     if ($this->season) {
         # use midpoint of season to get season dates for filter
         $start_year = substr($this->season, 0, 4);
         $end_year = strlen($this->season) == 7 ? $start_year + 1 : $start_year;
         if ($start_year == $end_year) {
             $season_dates = Season::SeasonDates(mktime(0, 0, 0, 7, 1, $start_year));
         } else {
             $season_dates = Season::SeasonDates(mktime(0, 0, 0, 12, 31, $start_year));
         }
         $statistics_manager->FilterAfterDate($season_dates[0]);
         $statistics_manager->FilterBeforeDate($season_dates[1]);
         $this->statistics_query .= "&from=" . $season_dates[0] . "&to=" . $season_dates[1];
     }
     $statistics_manager->FilterMaxResults(10);
     $this->most_runs = $statistics_manager->ReadBestPlayerAggregate("runs_scored");
     $this->most_wickets = $statistics_manager->ReadBestPlayerAggregate("wickets");
     $this->most_catches = $statistics_manager->ReadBestPlayerAggregate("catches");
     $this->most_run_outs = $statistics_manager->ReadBestPlayerAggregate("run_outs");
     $this->most_player_of_match = $statistics_manager->ReadBestPlayerAggregate("player_of_match");
     unset($statistics_manager);
 }
 function OnLoadPageData()
 {
     # check parameter
     if (!isset($_GET['item']) or !is_numeric($_GET['item'])) {
         $this->Redirect();
     }
     # new data managers
     $ground_manager = new GroundManager($this->GetSettings(), $this->GetDataConnection());
     # get ground
     $ground_manager->ReadById(array($_GET['item']));
     $this->ground = $ground_manager->GetFirst();
     # must have found a ground
     if (!$this->ground instanceof Ground) {
         $this->Redirect();
     }
     # Get teams based at the ground
     require_once "stoolball/team-manager.class.php";
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     $team_manager->FilterByActive(true);
     $team_manager->FilterByGround(array($this->ground->GetId()));
     $team_manager->FilterByTeamType(array(Team::CLOSED_GROUP, Team::OCCASIONAL, Team::REGULAR, Team::REPRESENTATIVE, Team::SCHOOL_YEARS, Team::SCHOOL_CLUB, Team::SCHOOL_OTHER));
     $team_manager->ReadTeamSummaries();
     $this->ground->Teams()->SetItems($team_manager->GetItems());
     # Update search engine
     if ($this->ground->GetSearchUpdateRequired()) {
         require_once "search/ground-search-adapter.class.php";
         $this->SearchIndexer()->DeleteFromIndexById("ground" . $this->ground->GetId());
         $adapter = new GroundSearchAdapter($this->ground);
         $this->SearchIndexer()->Index($adapter->GetSearchableItem());
         $this->SearchIndexer()->CommitChanges();
         $ground_manager->SearchUpdated($this->ground->GetId());
     }
     unset($team_manager);
     unset($ground_manager);
     # Read statistics highlights for the ground
     require_once 'stoolball/statistics/statistics-manager.class.php';
     $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
     $statistics_manager->FilterByGround(array($this->ground->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);
 }
 private function IndexGrounds()
 {
     require_once 'stoolball/ground-manager.class.php';
     require_once "stoolball/team-manager.class.php";
     require_once 'search/ground-search-adapter.class.php';
     $this->SearchIndexer()->DeleteFromIndexByType("ground");
     $manager = new GroundManager($this->GetSettings(), $this->GetDataConnection());
     $manager->FilterByActive(true);
     $manager->ReadAll();
     $grounds = $manager->GetItems();
     unset($manager);
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     foreach ($grounds as $ground) {
         /* @var $ground Ground */
         # Get teams based at the ground
         $team_manager->FilterByGround(array($ground->GetId()));
         $team_manager->FilterByActive(true);
         $team_manager->ReadTeamSummaries();
         $teams = $team_manager->GetItems();
         $ground->Teams()->SetItems($teams);
         $adapter = new GroundSearchAdapter($ground);
         $this->SearchIndexer()->Index($adapter->GetSearchableItem());
     }
     $this->SearchIndexer()->CommitChanges();
     unset($team_manager);
 }
 function OnLoadPageData()
 {
     # Require an API key to include personal contact details to avoid spam bots picking them up
     $api_keys = $this->GetSettings()->GetApiKeys();
     $valid_key = false;
     if (isset($_GET['key']) and in_array($_GET['key'], $api_keys)) {
         $valid_key = true;
     }
     $data = array();
     $data[] = array("Club/ facility name", "Address 1", "Address 2", "Address 3", "Address 4", "Address 5", "City", "Postcode", "Country", "Tel", "Email", "Website", "Activities", "Opening times");
     require_once 'stoolball/team-manager.class.php';
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     $team_manager->FilterByActive(true);
     $team_manager->FilterByTeamType(array(Team::REGULAR));
     $team_manager->ReadById();
     while ($team_manager->MoveNext()) {
         /* @var $team Team */
         $team = $team_manager->GetItem();
         # NHS choices can only import records with a postcode
         if (!$team->GetGround()->GetAddress()->GetPostcode()) {
             continue;
         }
         $address = array();
         if ($team->GetGround()->GetAddress()->GetSaon()) {
             $address[] = $team->GetGround()->GetAddress()->GetSaon();
         }
         if ($team->GetGround()->GetAddress()->GetPaon()) {
             $address[] = $team->GetGround()->GetAddress()->GetPaon();
         }
         if ($team->GetGround()->GetAddress()->GetStreetDescriptor()) {
             $address[] = $team->GetGround()->GetAddress()->GetStreetDescriptor();
         }
         if ($team->GetGround()->GetAddress()->GetLocality()) {
             $address[] = $team->GetGround()->GetAddress()->GetLocality();
         }
         if ($team->GetGround()->GetAddress()->GetAdministrativeArea()) {
             $address[] = $team->GetGround()->GetAddress()->GetAdministrativeArea();
         }
         $data[] = array($team->GetName() . " Stoolball Club", isset($address[0]) ? $address[0] : "", isset($address[1]) ? $address[1] : "", isset($address[2]) ? $address[2] : "", isset($address[3]) ? $address[3] : "", isset($address[4]) ? $address[4] : "", $team->GetGround()->GetAddress()->GetTown(), $team->GetGround()->GetAddress()->GetPostcode(), "England", $valid_key ? $team->GetContactPhone() : "", $valid_key ? $team->GetContactEmail() : "", $team->GetWebsiteUrl() ? $team->GetWebsiteUrl() : "https://" . $this->GetSettings()->GetDomain() . $team->GetNavigateUrl(), "stoolball", preg_replace('/\\[[^]]+\\]/', "", $team->GetPlayingTimes()));
     }
     unset($team_manager);
     require_once "data/csv.class.php";
     CSV::PublishData($data);
     # Test code only. Comment out CSV publish line above to enable display as a table.
     require_once "xhtml/tables/xhtml-table.class.php";
     $table = new XhtmlTable();
     $table->BindArray($data, false, false);
     echo $table;
 }
 function OnLoadPageData()
 {
     # get id of season
     $i_id = $this->season_manager->GetItemId($this->season);
     # read season data when first asked to edit a season
     if ($i_id and !$this->IsPostback()) {
         $this->season_manager->ReadById(array($i_id));
         $this->season = $this->season_manager->GetFirst();
     }
     # get all teams
     $this->team_manager->SetGroupInactiveLast(false);
     $this->team_manager->ReadAll();
     $this->edit->SetTeams($this->team_manager->GetItems());
     # tidy up
     unset($this->season_manager);
     unset($this->team_manager);
 }
 function OnLoadPageData()
 {
     # new data manager
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     $team_manager->FilterByActive(true);
     # Check for player type
     $this->player_type = null;
     if (isset($_GET['player'])) {
         if ($_GET['player'] == "past") {
             $this->player_type = 0;
             $team_manager->FilterByActive(false);
         } else {
             $this->player_type = PlayerType::Parse($_GET['player']);
             $a_player_types = is_null($this->player_type) ? null : array($this->player_type);
             if ($this->player_type == PlayerType::JUNIOR_MIXED) {
                 $a_player_types[] = PlayerType::GIRLS;
                 $a_player_types[] = PlayerType::BOYS;
             }
             $team_manager->FilterByPlayerType($a_player_types);
         }
     }
     if (isset($_GET['area']) and $_GET["area"]) {
         $this->administrative_area = preg_replace('/[^a-z]/', "", strtolower($_GET['area']));
         if ($this->administrative_area) {
             $team_manager->FilterByAdministrativeArea(array($this->administrative_area));
         }
     }
     # Get the counties for the filter
     $this->areas = $team_manager->ReadAdministrativeAreas();
     if ($this->administrative_area) {
         # read all teams matching the applied filter
         $team_manager->ReadTeamSummaries();
         $this->teams = $team_manager->GetItems();
     }
     unset($team_manager);
 }
 function OnLoadPageData()
 {
     # Require an API key to include personal contact details to avoid spam bots picking them up
     $api_keys = $this->GetSettings()->GetApiKeys();
     $valid_key = false;
     if (isset($_GET['key']) and in_array($_GET['key'], $api_keys)) {
         $valid_key = true;
     }
     $data = array();
     $data[] = array("Team id", "Team name", "Player type", "Home ground name", "Street name", "Locality", "Town", "Administrative area", "Postcode", "Country", "Latitude", "Longitude", "Contact phone", "Contact email", "Website", "Description");
     require_once 'stoolball/team-manager.class.php';
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     $team_manager->FilterByActive(true);
     $team_manager->FilterByTeamType(array(Team::REGULAR));
     $team_manager->ReadById();
     while ($team_manager->MoveNext()) {
         $team = $team_manager->GetItem();
         /* @var $team Team */
         # Spogo can only import records with contact details
         if (!$team->GetContactPhone() and !$team->GetContactEmail()) {
             continue;
         }
         # Combine free text fields into a description field
         $description = $team->GetIntro();
         if ($description) {
             $description .= "\n\n";
         }
         if ($team->GetPlayingTimes()) {
             $description .= $team->GetPlayingTimes() . "\n\n";
         }
         if ($team->GetCost()) {
             $description .= $team->GetCost();
         }
         # Add this team to the data array
         $data[] = array($team->GetId(), $team->GetName() . " Stoolball Club", PlayerType::Text($team->GetPlayerType()), $team->GetGround()->GetAddress()->GetPaon(), $team->GetGround()->GetAddress()->GetStreetDescriptor(), $team->GetGround()->GetAddress()->GetLocality(), $team->GetGround()->GetAddress()->GetTown(), $team->GetGround()->GetAddress()->GetAdministrativeArea(), $team->GetGround()->GetAddress()->GetPostcode(), "England", $team->GetGround()->GetAddress()->GetLatitude(), $team->GetGround()->GetAddress()->GetLongitude(), $valid_key ? $team->GetContactPhone() : "", $valid_key ? $team->GetContactEmail() : "", $team->GetWebsiteUrl() ? $team->GetWebsiteUrl() : "https://" . $this->GetSettings()->GetDomain() . $team->GetNavigateUrl(), trim(html_entity_decode(strip_tags($description), ENT_QUOTES)));
     }
     unset($team_manager);
     require_once "data/csv.class.php";
     CSV::PublishData($data);
     # Test code only. Comment out CSV publish line above to enable display as a table.
     require_once "xhtml/tables/xhtml-table.class.php";
     $table = new XhtmlTable();
     $table->BindArray($data, false, false);
     echo $table;
 }
 function OnLoadPageData()
 {
     # new data managers
     $o_comp_manager = new CompetitionManager($this->GetSettings(), $this->GetDataConnection());
     $o_team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     # get comps
     $o_comp_manager->SetExcludeInactive(true);
     $o_comp_manager->ReadAllSummaries();
     $this->a_comps = $o_comp_manager->GetItems();
     # get teams
     $o_team_manager->FilterByActive(true);
     foreach ($this->a_comps as $o_comp) {
         /* @var $o_comp Competition */
         $a_seasons = array($o_comp->GetLatestSeason()->GetId());
         $o_team_manager->ReadBySeasonId($a_seasons);
         while ($o_team_manager->MoveNext()) {
             $o_comp->GetLatestSeason()->AddTeam($o_team_manager->GetItem());
         }
         $o_team_manager->Clear();
     }
     # tidy up
     unset($o_comp_manager);
     unset($o_team_manager);
 }
 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);
 }
 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()
 {
     # Read the player data if (a) it's not a new player and (b) it's not in the postback data
     if ($this->player->GetId() and !$this->IsPostback()) {
         $this->player_manager->ReadPlayerById($this->player->GetId());
         $this->player = $this->player_manager->GetFirst();
     }
     unset($this->player_manager);
     # ensure we have a player
     if (!$this->player instanceof Player) {
         $this->Redirect();
     }
     # if it's a new player, get the team details
     if (!$this->player->GetId() or $this->add_player_already_exists) {
         if (!$this->team instanceof Team) {
             require_once "stoolball/team-manager.class.php";
             $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
             $team_manager->ReadById(array($this->player->Team()->GetId()));
             $this->team = $team_manager->GetFirst();
             unset($team_manager);
         }
         $this->player->Team()->SetName($this->team->GetName());
         $this->player->Team()->SetShortUrl($this->team->GetShortUrl());
     }
     # ensure we have permission
     $this->CheckForPermission($this->player->Team());
 }
 function OnLoadPageData()
 {
     /* @var Team $team */
     # check parameter
     if (!isset($_GET['item']) or !is_numeric($_GET['item'])) {
         $this->Redirect();
     }
     # new data manager
     $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
     $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
     # get teams
     $team_manager->FilterByTeamType(array());
     $team_manager->ReadById(array($_GET['item']));
     $this->team = $team_manager->GetFirst();
     # must have found a team
     if (!$this->team instanceof Team) {
         $this->Redirect('/teams/');
     }
     # Update search engine
     if ($this->team->GetSearchUpdateRequired()) {
         require_once "search/team-search-adapter.class.php";
         $this->SearchIndexer()->DeleteFromIndexById("team" . $this->team->GetId());
         $adapter = new TeamSearchAdapter($this->team);
         $this->SearchIndexer()->Index($adapter->GetSearchableItem());
         $this->SearchIndexer()->CommitChanges();
         $team_manager->SearchUpdated($this->team->GetId());
     }
     unset($team_manager);
     $this->is_one_time_team = $this->team->GetTeamType() == Team::ONCE;
     # get matches and match stats
     if (!$this->is_one_time_team) {
         $a_season_dates = Season::SeasonDates();
         $this->season_key = date('Y', $a_season_dates[0]);
         if ($this->season_key != date('Y', $a_season_dates[1])) {
             $this->season_key .= "/" . date('y', $a_season_dates[1]);
         }
         $match_manager->FilterByDateStart($a_season_dates[0]);
     }
     $match_manager->FilterByTeam(array($this->team->GetId()));
     $match_manager->ReadMatchSummaries();
     $this->a_matches = $match_manager->GetItems();
     unset($match_manager);
     $club = $this->team->GetClub();
     $this->has_facebook_group_url = ($club->GetFacebookUrl() and strpos($club->GetFacebookUrl(), '/groups/') !== false);
     $this->has_facebook_page_url = ($club->GetFacebookUrl() and !$this->has_facebook_group_url);
     if (!$this->has_facebook_page_url) {
         require_once 'stoolball/statistics/statistics-manager.class.php';
         $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
         $statistics_manager->FilterByTeam(array($this->team->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);
     }
     # Get whether to show add league/cup links
     $season_manager = new SeasonManager($this->GetSettings(), $this->GetDataConnection());
     $season_manager->ReadCurrentSeasonsByTeamId(array($this->team->GetId()), array(MatchType::CUP, MatchType::LEAGUE));
     $this->seasons = $season_manager->GetItems();
     unset($season_manager);
 }
 /**
  * Saves the links between a match and the teams playing in it
  * @param $match
  * @return void
  */
 public function SaveTeams(Match $match)
 {
     if (!$match->GetId()) {
         return;
     }
     $match_id = Sql::ProtectNumeric($match->GetId());
     $match_team_ids = array();
     if ($match->GetHomeTeamId()) {
         $match_team_ids[] = $this->EnsureTeamInMatch($match, $match->GetHomeTeamId(), TeamRole::Home());
     }
     $is_tournament = $match->GetMatchType() == MatchType::TOURNAMENT;
     $tournament = null;
     if ($is_tournament) {
         require_once "stoolball/team-manager.class.php";
         $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
         # For a tournament, attempt to save the maxiumum number of teams
         $sql = "UPDATE nsa_match SET max_tournament_teams = " . Sql::ProtectNumeric($match->GetMaximumTeamsInTournament(), true, false) . ",\r\n                    tournament_spaces = " . Sql::ProtectNumeric($match->GetSpacesLeftInTournament(), true, false) . "\r\n                    WHERE match_id = {$match_id}";
         $this->GetDataConnection()->query($sql);
     }
     $away_teams = $match->GetAwayTeams();
     foreach ($away_teams as $away_team) {
         $away_team_id = $away_team->GetId();
         # If this is a tournament we may be adding teams based on the name rather than the ID
         if (!$away_team_id and $is_tournament) {
             if (is_null($tournament)) {
                 # Make sure we have full details for the tournament, in order to build any tournament teams
                 $this->ReadByMatchId(array($match->GetId()));
                 $tournament = $this->GetFirst();
             }
             $away_team_id = $team_manager->SaveOrMatchTournamentTeam($tournament, $away_team);
         }
         # Ensure we now have an ID, or the following queries will be invalid
         if ($away_team_id) {
             $match_team_ids[] = $this->EnsureTeamInMatch($match, $away_team_id, TeamRole::Away());
         }
     }
     # See if there are any other teams for this match, aside from those we've just confirmed or added.
     # Those will be teams just deleted.
     $match_table = $this->GetSettings()->GetTable('Match');
     $mt = $this->GetSettings()->GetTable('MatchTeam');
     $stats = $this->GetSettings()->GetTable('PlayerMatch');
     $sql = "SELECT match_team_id, team.team_id, team.team_type \r\n\t\t          FROM {$mt} INNER JOIN nsa_team AS team ON {$mt}.team_id = team.team_id\r\n\t\t          WHERE match_id = {$match_id}";
     if (count($match_team_ids)) {
         $sql .= " AND match_team_id NOT IN (" . implode(",", $match_team_ids) . ")";
     }
     $result = $this->GetDataConnection()->query($sql);
     $delete_match_team_ids = array();
     $delete_team_ids = array();
     while ($row = $result->fetch()) {
         $delete_match_team_ids[] = $row->match_team_id;
         if ($is_tournament and $row->team_type == Team::ONCE) {
             $delete_team_ids[] = $row->team_id;
         }
     }
     if (count($delete_match_team_ids)) {
         # If there are, delete them and their dependent records
         $delete_match_team_ids = implode(",", $delete_match_team_ids);
         $batting = $this->GetSettings()->GetTable('Batting');
         $bowling = $this->GetSettings()->GetTable('Bowling');
         $this->LoggedQuery("DELETE FROM {$batting} WHERE match_team_id IN ({$delete_match_team_ids})");
         $this->LoggedQuery("DELETE FROM {$bowling} WHERE match_team_id IN ({$delete_match_team_ids})");
         $this->LoggedQuery("DELETE FROM {$stats} WHERE match_team_id IN ({$delete_match_team_ids})");
         $this->LoggedQuery("DELETE FROM {$mt} WHERE match_team_id IN ({$delete_match_team_ids})");
         $this->RemovePlayerOfTheMatchIfTeamRemoved($match_id, "player_of_match_id");
         $this->RemovePlayerOfTheMatchIfTeamRemoved($match_id, "player_of_match_home_id");
         $this->RemovePlayerOfTheMatchIfTeamRemoved($match_id, "player_of_match_away_id");
     }
     # make sure the player statistics have the correct opposition
     $this->GetDataConnection()->query("UPDATE {$stats} SET opposition_id = NULL WHERE match_id = {$match_id}");
     foreach ($match_team_ids as $match_team_id) {
         $sql = "SELECT team_id\r\n\t\t\t\t\t\tFROM {$mt} INNER JOIN {$match_table} m ON {$mt}.match_id = m.match_id\r\n\t\t\t\t\t\tWHERE m.match_id = (SELECT match_id FROM {$mt} WHERE match_team_id = {$match_team_id})\r\n\t\t\t\t\t\tAND {$mt}.match_team_id != {$match_team_id}\r\n\t\t\t\t\t\tAND team_role IN (" . TeamRole::Home() . ", " . TeamRole::Away() . ")";
         $data = $this->GetDataConnection()->query($sql);
         $data_row = $data->fetch();
         if ($data_row) {
             $this->GetDataConnection()->query("UPDATE {$stats} SET opposition_id = {$data_row->team_id} WHERE match_team_id = {$match_team_id}");
         }
     }
     # If we found any once-only tournament teams that were removed, delete them
     if ($is_tournament) {
         if (count($delete_team_ids)) {
             $team_manager->Delete($delete_team_ids);
         }
         unset($team_manager);
     }
     $result->closeCursor();
 }
    public function OnLoadPageData()
    {
        require_once "stoolball/team-manager.class.php";
        $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
        $team_manager->FilterByActive(true);
        if (isset($_GET['except'])) {
            $except = explode(",", $_GET['except']);
            # Make sure all values are numeric. If not, ignore them all.
            foreach ($except as $id) {
                if (!is_numeric($id)) {
                    $except = array();
                    break;
                }
            }
            $team_manager->FilterExceptTeams($except);
        }
        $team_manager->ReadTeamSummaries();
        $teams = $team_manager->GetItems();
        unset($team_manager);
        if (count($teams)) {
            # Build up the data to display in the autocomplete dropdown
            $suggestions = array();
            foreach ($teams as $team) {
                /* @var $team Team */
                $escaped_name = str_replace("'", "\\'", $team->GetNameAndType());
                # escape single quotes because this will become JS string
                $suggestions[] = "{label:\"" . $escaped_name . "\"}";
                # escape single quotes for JS string
            }
            # Write those names as a JS array
            ?>
$(function()
{
	var teams = [<?php 
            echo implode(",\n", $suggestions);
            ?>
];

	// find anywhere a team's name should be entered
	$("input.team", "form").each(enableSuggestions);

	function enableSuggestions()
	{
		// hook up the autocomplete to work with just the team's name, not their supporting info
		var input = $(this);
		if (!input.hasClass("autocomplete"))
		{
			input.autocomplete({source:teams}).data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append("<a>" + item.label + "</a>")
					.appendTo( ul )};
		}
		else
		{
			input.autocomplete("option","source",teams);
		}
	}
});
			<?php 
        }
        exit;
    }
 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 $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);
     }
 }