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);
 }
 public function OnPostback()
 {
     # If there's no id, ensure no match object is created. Page will then display a "match not found" message.
     # There's a separate page for adding matches, even for admins.
     if (!$this->editor->GetDataObjectId()) {
         return;
     }
     # Get the submitted match
     $this->match = $this->editor->GetDataObject();
     # Because this is a new request, we need to reverify whether this is the match owner before letting anything happen.
     # Can't trust that info from a postback so MUST go to the database to check it.
     $this->match_manager->ReadByMatchId(array($this->editor->GetDataObjectId()));
     $check_match = $this->match_manager->GetFirst();
     $this->b_user_is_match_owner = ($check_match instanceof Match and AuthenticationManager::GetUser()->GetId() == $check_match->GetAddedBy()->GetId());
     # Don't wan't to edit tournaments on this page, so even as admin make sure we're not trying to save one.
     # Can't change the match type, so find out what that is from the db too.
     $this->b_is_tournament = $check_match->GetMatchType() == MatchType::TOURNAMENT;
     # Check whether cancel was clicked
     if ($this->editor->CancelClicked()) {
         # If so, get the match's short URL and redirect
         $this->match_manager->ExpandMatchUrl($this->match);
         $this->Redirect($this->match->GetNavigateUrl());
     }
     # save data if valid
     if ($this->IsValid() and !$this->b_is_tournament) {
         # Save player of match
         $this->match_manager->SaveHighlights($this->match);
         $this->match_manager->ExpandMatchUrl($this->match);
         # Add comment if provided
         if (trim($this->match->GetNewComment())) {
             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());
             $item_to_comment_on = new ReviewItem($this->GetSettings());
             $item_to_comment_on->SetType(ContentType::STOOLBALL_MATCH);
             $item_to_comment_on->SetId($this->match->GetId());
             $item_to_comment_on->SetNavigateUrl("https://" . $this->GetSettings()->GetDomain() . $this->match->GetNavigateUrl());
             $message = $topic_manager->SaveComment($item_to_comment_on, $this->match->GetNewComment());
             # send subscription emails
             $subs_manager = new SubscriptionManager($this->GetSettings(), $this->GetDataConnection());
             $subs_manager->SendCommentsSubscriptions($item_to_comment_on, $message);
             unset($subs_manager);
         }
         # Match may have been updated so send an email
         $this->match_manager->NotifyMatchModerator($this->match->GetId());
         # Show user the match, so they can see update was applied
         $this->Redirect($this->match->GetNavigateUrl());
     }
 }
 function OnPostback()
 {
     if ($this->editor->GetDataObjectId()) {
         # Because this is a new request we need to reverify that this is the match owner before letting anything happen.
         # Can't trust that info from a postback so MUST go to the database to check it.
         $this->match_manager->ReadByMatchId(array($this->editor->GetDataObjectId()));
         $check_match = $this->match_manager->GetFirst();
         $this->b_user_is_match_owner = ($check_match instanceof Match and AuthenticationManager::GetUser()->GetId() == $check_match->GetAddedBy()->GetId());
         # This page is only for tournaments, so check that against the db too
         $this->b_is_tournament = $check_match->GetMatchType() == MatchType::TOURNAMENT;
     } else {
         # Not an entirely correct error for there being no match id on postback,
         # but no match = not the owner, and most importantly it will prevent the
         # match being saved or the edit form being shown.
         $this->b_user_is_match_owner = false;
     }
     # get object
     $this->tournament = $this->editor->GetDataObject();
     # Check whether cancel was clicked
     if ($this->editor->CancelClicked()) {
         $this->match_manager->ExpandMatchUrl($this->tournament);
         if ($this->adding) {
             http_response_code(303);
             $this->Redirect($this->tournament->GetDeleteNavigateUrl());
         } else {
             # Show the tournament
             $this->Redirect($this->tournament->GetNavigateUrl());
         }
     }
     # save data if valid
     if ($this->IsValid()) {
         # Confirm match is being saved as a tournament
         $this->b_is_tournament = $this->b_is_tournament and $this->tournament->GetMatchType() == MatchType::TOURNAMENT;
         # Check that the requester has permission to update this match
         if (($this->b_user_is_match_admin or $this->b_user_is_match_owner) and $this->b_is_tournament) {
             # Save the teams in the tournament
             $this->match_manager->SaveTeams($this->tournament);
             $this->match_manager->NotifyMatchModerator($this->tournament->GetId());
             $this->match_manager->ExpandMatchUrl($this->tournament);
             http_response_code(303);
             if ($this->adding) {
                 $this->Redirect($this->tournament->AddTournamentCompetitionsUrl());
             } else {
                 $this->Redirect($this->tournament->GetNavigateUrl());
             }
         }
     }
 }
 function OnPostback()
 {
     # get object
     $this->tournament = $this->editor->GetDataObject();
     if ($this->editor->GetDataObjectId()) {
         # Because this is a new request we need to reverify security details before letting anything happen.
         # Can't trust that info from a postback so MUST go to the database to check it.
         $this->match_manager->ReadByMatchId(array($this->editor->GetDataObjectId()));
         $check_match = $this->match_manager->GetFirst();
         if ($check_match instanceof Match) {
             # This page is only for tournaments, so check that against the db
             $this->b_is_tournament = $check_match->GetMatchType() == MatchType::TOURNAMENT;
             /* The editor requires the teams in the tournament to populate the dropdown and to come up with a
              * match title, and it doesn't have them when recreating the tournament from the postback data. 
              * Since we have $check_match available from the database anyway, get the teams from there. */
             foreach ($check_match->GetAwayTeams() as $team) {
                 $this->tournament->AddAwayTeam($team);
             }
         }
     } else {
         # Error for there being no match id on postback,
         $this->b_is_tournament = false;
     }
     # Check whether cancel was clicked
     if ($this->editor->CancelClicked()) {
         $this->match_manager->ExpandMatchUrl($this->tournament);
         $this->Redirect($this->tournament->GetNavigateUrl());
     }
     # save data if valid
     if ($this->IsValid()) {
         # Confirm match is being saved as a tournament
         $this->b_is_tournament = $this->b_is_tournament and $this->tournament->GetMatchType() == MatchType::TOURNAMENT;
         # Check that the requester has permission to update this match
         if ($this->b_is_tournament) {
             # Save the matches in the tournament
             $this->match_manager->SaveMatchesInTournament($this->tournament);
             $this->match_manager->NotifyMatchModerator($this->tournament->GetId());
             $this->match_manager->ExpandMatchUrl($this->tournament);
             http_response_code(303);
             $this->Redirect($this->tournament->GetNavigateUrl());
         }
     }
 }
 public function OnPostback()
 {
     # If there's no id, ensure no match object is created. Page will then display a "match not found" message.
     # There's a separate page for adding matches, even for admins.
     if (!$this->editor->GetDataObjectId()) {
         return;
     }
     # Get the submitted match
     $this->match = $this->editor->GetDataObject();
     # Because this is a new request, we need to reverify whether this is the match owner before letting anything happen.
     # Can't trust that info from a postback so MUST go to the database to check it.
     $this->match_manager->ReadByMatchId(array($this->editor->GetDataObjectId()));
     $check_match = $this->match_manager->GetFirst();
     $this->b_user_is_match_owner = ($check_match instanceof Match and AuthenticationManager::GetUser()->GetId() == $check_match->GetAddedBy()->GetId());
     # Don't wan't to edit tournaments on this page, so even as admin make sure we're not trying to save one.
     # Can't change the match type, so find out what that is from the db too.
     $this->b_is_tournament = $check_match->GetMatchType() == MatchType::TOURNAMENT;
     # Check whether cancel was clicked
     if ($this->editor->CancelClicked()) {
         # Match may have been updated so send an email
         $this->match_manager->NotifyMatchModerator($this->match->GetId());
         # If so, get the match's short URL and redirect
         $this->match_manager->ExpandMatchUrl($this->match);
         $this->Redirect($this->match->GetNavigateUrl());
     }
     # save data if valid
     if ($this->IsValid() and !$this->b_is_tournament) {
         switch ($this->editor->GetCurrentPage()) {
             case ScorecardEditControl::FIRST_INNINGS:
                 $this->match_manager->SaveScorecard($this->match, true, $this->SearchIndexer());
                 $this->editor->SetCurrentPage(ScorecardEditControl::SECOND_INNINGS);
                 break;
             case ScorecardEditControl::SECOND_INNINGS:
                 $this->match_manager->SaveScorecard($this->match, false, $this->SearchIndexer());
                 $this->match_manager->ExpandMatchUrl($this->match);
                 http_response_code(303);
                 $this->Redirect($this->match->EditHighlightsUrl());
                 break;
         }
     }
 }
 public function __construct(Match $match)
 {
     $this->match = $match;
     $this->searchable = new SearchItem("match", "match" . $match->GetId(), $match->GetNavigateUrl());
     $this->searchable->Title($match->GetTitle() . ", " . $match->GetStartTimeFormatted(true, false));
     $this->searchable->Description($this->GetSearchDescription());
     $this->searchable->FullText($match->GetNotes());
     $this->searchable->RelatedLinksHtml('<ul>' . '<li><a href="' . $match->GetNavigateUrl() . '/statistics">Statistics</a></li>' . '<li><a href="' . $match->GetCalendarNavigateUrl() . '">Add to calendar</a></li>' . '<li><a href="' . $match->GetEditNavigateUrl() . '">Update result</a></li>' . '</ul>');
     # Assign more weight to newer matches
     $weight = $match->GetStartTime() / 60 / 60 / 24 / 365;
     $this->searchable->WeightWithinType($weight);
 }
 function OnPostback()
 {
     # Get the match info and store it
     $i_id = $this->manager->GetItemId($this->match);
     $this->manager->ReadByMatchId(array($i_id));
     $this->match = $this->manager->GetFirst();
     if (!$this->match instanceof Match) {
         # This can be the case if the back button is used to go back to the "match has been deleted" page.
         $this->b_deleted = true;
         return;
     }
     # Check whether cancel was clicked
     if (isset($_POST['cancel'])) {
         $this->Redirect($this->match->GetNavigateUrl());
     }
     # Check whether delete was clicked
     if (isset($_POST['delete'])) {
         # Check again that the requester has permission to delete this match
         $has_permission = (AuthenticationManager::GetUser()->Permissions()->HasPermission(PermissionType::MANAGE_MATCHES) or AuthenticationManager::GetUser()->GetId() == $this->match->GetAddedBy()->GetId());
         if ($has_permission) {
             # Delete the match
             $this->manager->DeleteMatch(array($i_id));
             # Remove match, and all dependent tournament matches, from search results
             foreach ($this->match->GetMatchesInTournament() as $tournament_match) {
                 $this->SearchIndexer()->DeleteFromIndexById("match" . $tournament_match->GetId());
             }
             $this->SearchIndexer()->DeleteFromIndexById("match" . $this->match->GetId());
             $this->SearchIndexer()->CommitChanges();
             require_once 'stoolball/data-change-notifier.class.php';
             $notifier = new DataChangeNotifier($this->GetSettings());
             $notifier->MatchUpdated($this->match, AuthenticationManager::GetUser(), false, true);
             # Update 'next 5 matches'
             $this->manager->ReadNext();
             $this->a_next_matches = $this->manager->GetItems();
             # Note success
             $this->b_deleted = true;
         }
     }
 }
 /**
  * Creates the controls when the editor is in its fixture view
  *
  */
 private function CreateFixtureControls(Match $match, XhtmlElement $match_box)
 {
     $css_class = 'TournamentEdit';
     if ($this->GetCssClass()) {
         $css_class .= ' ' . $this->GetCssClass();
     }
     $match_outer_1 = new XhtmlElement('div');
     $match_outer_1->SetCssClass($css_class);
     $this->SetCssClass('');
     $match_outer_1->SetXhtmlId($this->GetNamingPrefix());
     $match_outer_2 = new XhtmlElement('div');
     $this->AddControl($match_outer_1);
     $match_outer_1->AddControl($match_outer_2);
     $match_outer_2->AddControl($match_box);
     if ($match->GetId()) {
         $heading = "Edit tournament";
     } else {
         $heading = "Add your tournament";
     }
     if ($this->show_step_number) {
         $heading .= ' &#8211; step 1 of 3';
     }
     $o_title_inner_1 = new XhtmlElement('span', $heading);
     $o_title_inner_2 = new XhtmlElement('span', $o_title_inner_1);
     $o_title_inner_3 = new XhtmlElement('span', $o_title_inner_2);
     $match_box->AddControl(new XhtmlElement('h2', $o_title_inner_3, "large"));
     # Tournament title
     $suggested_title = $match->GetTitle();
     if (isset($this->context_season)) {
         $suggested_title = $this->GetContextSeason()->GetCompetition()->GetName();
         if (strpos(strtolower($suggested_title), 'tournament') === false) {
             $suggested_title .= ' tournament';
         }
     } else {
         if (isset($this->context_team)) {
             $suggested_title = $this->GetContextTeam()->GetName();
             if (strpos(strtolower($suggested_title), 'tournament') === false) {
                 $suggested_title .= ' tournament';
             }
         }
     }
     if ($suggested_title == "To be confirmed tournament") {
         $suggested_title = "";
     }
     if ($suggested_title == "To be confirmed v To be confirmed") {
         $suggested_title = "";
     }
     $title = new TextBox($this->GetNamingPrefix() . 'Title', $suggested_title, $this->IsValidSubmit());
     $title->SetMaxLength(200);
     $match_box->AddControl(new FormPart('Tournament name', $title));
     # Open or invite?
     require_once 'xhtml/forms/radio-button.class.php';
     $qualify_set = new XhtmlElement('fieldset');
     $qualify_set->SetCssClass('formPart radioButtonList');
     $qualify_set->AddControl(new XhtmlElement('legend', 'Who can play?', 'formLabel'));
     $qualify_radios = new XhtmlElement('div', null, 'formControl');
     $qualify_set->AddControl($qualify_radios);
     $qualify_radios->AddControl(new RadioButton($this->GetNamingPrefix() . 'Open', $this->GetNamingPrefix() . 'Qualify', 'any team may enter', MatchQualification::OPEN_TOURNAMENT, $match->GetQualificationType() === MatchQualification::OPEN_TOURNAMENT or !$match->GetId(), $this->IsValidSubmit()));
     $qualify_radios->AddControl(new RadioButton($this->GetNamingPrefix() . 'Qualify', $this->GetNamingPrefix() . 'Qualify', 'only invited or qualifying teams can enter', MatchQualification::CLOSED_TOURNAMENT, $match->GetQualificationType() === MatchQualification::CLOSED_TOURNAMENT, $this->IsValidSubmit()));
     $match_box->AddControl($qualify_set);
     # Player type
     $suggested_type = 2;
     if (isset($this->context_season)) {
         $suggested_type = $this->context_season->GetCompetition()->GetPlayerType();
     } elseif (isset($this->context_team)) {
         $suggested_type = $this->context_team->GetPlayerType();
     }
     if (!is_null($match->GetPlayerType())) {
         $suggested_type = $match->GetPlayerType();
     }
     # Saved value overrides suggestion
     $player_set = new XhtmlElement('fieldset');
     $player_set->SetCssClass('formPart radioButtonList');
     $player_set->AddControl(new XhtmlElement('legend', 'Type of teams', 'formLabel'));
     $player_radios = new XhtmlElement('div', null, 'formControl');
     $player_set->AddControl($player_radios);
     $player_radios_1 = new XhtmlElement('div', null, 'column');
     $player_radios_2 = new XhtmlElement('div', null, 'column');
     $player_radios->AddControl($player_radios_1);
     $player_radios->AddControl($player_radios_2);
     $player_radios_1->AddControl(new RadioButton($this->GetNamingPrefix() . 'Ladies', $this->GetNamingPrefix() . 'PlayerType', 'Ladies', 2, $suggested_type === 2, $this->IsValidSubmit()));
     $player_radios_1->AddControl(new RadioButton($this->GetNamingPrefix() . 'Mixed', $this->GetNamingPrefix() . 'PlayerType', 'Mixed', 1, $suggested_type === 1, $this->IsValidSubmit()));
     $player_radios_2->AddControl(new RadioButton($this->GetNamingPrefix() . 'Girls', $this->GetNamingPrefix() . 'PlayerType', 'Junior girls', 5, $suggested_type === 5, $this->IsValidSubmit()));
     $player_radios_2->AddControl(new RadioButton($this->GetNamingPrefix() . 'Children', $this->GetNamingPrefix() . 'PlayerType', 'Junior mixed', 4, $suggested_type === 6, $this->IsValidSubmit()));
     $match_box->AddControl($player_set);
     # How many?
     $per_side_box = new XhtmlSelect($this->GetNamingPrefix() . "Players", null, $this->IsValid());
     $per_side_box->SetBlankFirst(true);
     for ($i = 6; $i <= 16; $i++) {
         $per_side_box->AddControl(new XhtmlOption($i));
     }
     if ($match->GetIsMaximumPlayersPerTeamKnown()) {
         $per_side_box->SelectOption($match->GetMaximumPlayersPerTeam());
     } else {
         if (!$match->GetId()) {
             # Use eight as sensible default for new tournaments
             $per_side_box->SelectOption(8);
         }
     }
     $players_per_team = new XhtmlElement("label", $per_side_box);
     $players_per_team->AddAttribute("for", $this->GetNamingPrefix() . "Players");
     $players_per_team->AddControl(" players per team");
     $players_part = new FormPart("How many players?", $players_per_team);
     $players_part->AddCssClass("playersPerTeam");
     $match_box->AddControl($players_part);
     # Overs
     $overs_box = new XhtmlSelect($this->GetNamingPrefix() . "Overs", null, $this->IsValid());
     $overs_box->SetBlankFirst(true);
     for ($i = 2; $i <= 8; $i++) {
         $overs_box->AddControl(new XhtmlOption($i));
     }
     if ($match->GetIsOversKnown()) {
         $overs_box->SelectOption($match->GetOvers());
     }
     $overs_label = new XhtmlElement("label", "Overs per innings");
     $overs_label->AddAttribute("for", $overs_box->GetXhtmlId());
     $overs_part = new FormPart($overs_label, new XhtmlElement("div", $overs_box));
     $overs_part->AddCssClass("overs");
     $match_box->AddControl($overs_part);
     # Start date and time
     if (!$match->GetStartTime()) {
         # if no date set, use specified default
         if ($this->i_default_time) {
             $match->SetStartTime($this->i_default_time);
         } else {
             # if no date set and no default, default to today at 10.30am BST
             # NOTE that if this is a new tournament in an old season, this date won't be selected because the available
             # dates will be limited below and won't include today. It'll be the same day in the relevant year though.
             $i_now = gmdate('U');
             $match->SetStartTime(gmmktime(9, 30, 00, (int) gmdate('n', $i_now), (int) gmdate('d', $i_now), (int) gmdate('Y', $i_now)));
             $match->SetIsStartTimeKnown(true);
         }
     }
     $o_date = new DateControl($this->GetNamingPrefix() . 'Start', $match->GetStartTime(), $match->GetIsStartTimeKnown(), $this->IsValidSubmit());
     $o_date->SetShowTime(true);
     $o_date->SetRequireTime(false);
     $o_date->SetMinuteInterval(5);
     # if only one season to choose from, limit available dates to the length of that season
     if ($this->context_season instanceof Season) {
         if ($this->context_season->GetStartYear() == $this->context_season->GetEndYear()) {
             $i_mid_season = gmmktime(0, 0, 0, 6, 30, $this->context_season->GetStartYear());
         } else {
             $i_mid_season = gmmktime(0, 0, 0, 12, 31, $this->context_season->GetStartYear());
         }
         $season_dates = Season::SeasonDates($i_mid_season);
         $season_start_month = gmdate('n', $season_dates[0]);
         $season_end_month = gmdate('n', $season_dates[1]);
         if ($season_start_month) {
             $o_date->SetMonthStart($season_start_month);
         }
         if ($season_end_month) {
             $o_date->SetMonthEnd($season_end_month);
         }
         $season_start_year = $this->context_season->GetStartYear();
         $season_end_year = $this->context_season->GetEndYear();
         if ($season_start_year) {
             $o_date->SetYearStart($season_start_year);
         }
         if ($season_end_year) {
             $o_date->SetYearEnd($season_end_year);
         }
     }
     $o_date_part = new FormPart('When?', $o_date);
     $o_date_part->SetIsFieldset(true);
     $match_box->AddControl($o_date_part);
     # Where?
     $o_ground_list = new XhtmlSelect($this->GetNamingPrefix() . 'Ground');
     $o_ground_list->AddControl(new XhtmlOption("Don't know", -1));
     $o_ground_list->AddControl(new XhtmlOption('Not listed (type the address in the notes field)', -2));
     # Promote the most likely grounds to the top of the list
     $likely_ground_ids = array();
     if ($match->GetGroundId()) {
         $likely_ground_ids[] = $match->GetGroundId();
     }
     foreach ($this->probable_teams as $o_team) {
         $likely_ground_ids[] = $o_team->GetGround()->GetId();
     }
     if (isset($this->context_season)) {
         foreach ($this->context_season->GetTeams() as $o_team) {
             $likely_ground_ids[] = $o_team->GetGround()->GetId();
         }
     }
     if (isset($this->context_team) and is_object($this->context_team->GetGround())) {
         $likely_ground_ids[] = $this->context_team->GetGround()->GetId();
     }
     $likely_grounds = array();
     $a_other_grounds = array();
     /* @var $o_ground Ground */
     foreach ($this->grounds->GetItems() as $o_ground) {
         if (array_search($o_ground->GetId(), $likely_ground_ids) > -1) {
             $likely_grounds[] = $o_ground;
         } else {
             $a_other_grounds[] = $o_ground;
         }
     }
     # Add home grounds
     foreach ($likely_grounds as $o_ground) {
         $option = new XhtmlOption($o_ground->GetNameAndTown(), $o_ground->GetId());
         $option->SetGroupName('Likely grounds');
         $o_ground_list->AddControl($option);
     }
     # Add away grounds
     foreach ($a_other_grounds as $o_ground) {
         $option = new XhtmlOption($o_ground->GetNameAndTown(), $o_ground->GetId());
         $option->SetGroupName('Other grounds');
         $o_ground_list->AddControl($option);
     }
     # Select ground
     if ($match->GetGroundId()) {
         $o_ground_list->SelectOption($match->GetGroundId());
     } elseif (isset($this->context_team)) {
         $o_ground_list->SelectOption($this->context_team->GetGround()->GetId());
     }
     $o_ground_part = new FormPart('Where?', $o_ground_list);
     $match_box->AddControl($o_ground_part);
     # Notes
     $o_notes = new TextBox($this->GetNamingPrefix() . 'Notes', $match->GetNotes());
     $o_notes->SetMode(TextBoxMode::MultiLine());
     $o_notes_part = new FormPart('Notes<br />(remember to include contact details)', $o_notes);
     $match_box->AddControl($o_notes_part);
     # Remember short URL
     $o_short_url = new TextBox($this->GetNamingPrefix() . 'ShortUrl', $match->GetShortUrl());
     $o_short_url->SetMode(TextBoxMode::Hidden());
     $match_box->AddControl($o_short_url);
     # Note the context team to be added to the tournament by default
     if (isset($this->context_team)) {
         $context_team_box = new TextBox($this->GetNamingPrefix() . 'ContextTeam', $this->context_team->GetId());
         $context_team_box->SetMode(TextBoxMode::Hidden());
         $match_box->AddControl($context_team_box);
     }
     # Change Save button to "Next" button
     if ($this->show_step_number) {
         $this->SetButtonText('Next &raquo;');
     }
 }
    /**
     * @return void
     * @param Match $o_match
     * @desc Save the result and player(s) of the match to the database
     */
    public function SaveHighlights(Match $o_match)
    {
        # To add a result there must always already be a match to update
        if (!$o_match->GetId()) {
            return;
        }
        require_once "stoolball/player-manager.class.php";
        $player_manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
        # build query
        $s_match = $this->GetSettings()->GetTable('Match');
        $statistics = $this->GetSettings()->GetTable('PlayerMatch');
        $i_result = $o_match->Result()->GetResultType() <= 0 ? null : $o_match->Result()->GetResultType();
        $player_of_match = $player_manager->SaveOrMatchPlayer($o_match->Result()->GetPlayerOfTheMatch());
        $player_of_match_home = $player_manager->SaveOrMatchPlayer($o_match->Result()->GetPlayerOfTheMatchHome());
        $player_of_match_away = $player_manager->SaveOrMatchPlayer($o_match->Result()->GetPlayerOfTheMatchAway());
        # Check whether anything's changed and don't re-save if not
        $s_sql = 'SELECT match_id FROM ' . $s_match . ' ';
        $s_where = $this->SqlAddCondition("", 'match_result_id' . Sql::ProtectNumeric($i_result, true, true));
        $s_where = $this->SqlAddCondition($s_where, 'player_of_match_id ' . Sql::ProtectNumeric($player_of_match, true, true));
        $s_where = $this->SqlAddCondition($s_where, 'player_of_match_home_id ' . Sql::ProtectNumeric($player_of_match_home, true, true));
        $s_where = $this->SqlAddCondition($s_where, 'player_of_match_away_id ' . Sql::ProtectNumeric($player_of_match_away, true, true));
        $s_where = $this->SqlAddCondition($s_where, 'match_id = ' . Sql::ProtectNumeric($o_match->GetId()));
        $s_sql = $this->SqlAddWhereClause($s_sql, $s_where);
        $o_result = $this->GetDataConnection()->query($s_sql);
        if ($o_result->fetch()) {
            return;
        }
        # Should the match_title be regenerated?
        $s_sql = "SELECT custom_title FROM {$s_match} WHERE {$s_match}.match_id = " . Sql::ProtectNumeric($o_match->GetId());
        $o_result = $this->GetDataConnection()->query($s_sql);
        $o_row = $o_result->fetch();
        if (!is_null($o_row)) {
            $o_match->SetUseCustomTitle($o_row->custom_title);
        }
        # Save IDs of players affected by any change
        $affected_players = array();
        if (!is_null($player_of_match)) {
            $affected_players[] = $player_of_match;
        }
        if (!is_null($player_of_match_home)) {
            $affected_players[] = $player_of_match_home;
        }
        if (!is_null($player_of_match_away)) {
            $affected_players[] = $player_of_match_away;
        }
        $s_sql = "SELECT player_of_match_id, player_of_match_home_id, player_of_match_away_id FROM {$s_match} WHERE {$s_match}.match_id = " . Sql::ProtectNumeric($o_match->GetId());
        $o_result = $this->GetDataConnection()->query($s_sql);
        $row = $o_result->fetch();
        if (!is_null($row)) {
            if (!is_null($row->player_of_match_id)) {
                $affected_players[] = $row->player_of_match_id;
            }
            if (!is_null($row->player_of_match_home_id)) {
                $affected_players[] = $row->player_of_match_home_id;
            }
            if (!is_null($row->player_of_match_away_id)) {
                $affected_players[] = $row->player_of_match_away_id;
            }
        }
        # Update the main match record
        # All changes from here to master data are logged, because this method can be called from the public interface
        $sql = "UPDATE {$s_match} SET ";
        if (!$o_match->GetUseCustomTitle()) {
            $sql .= "match_title = " . Sql::ProtectString($this->GetDataConnection(), $o_match->GetTitle()) . ", ";
        }
        $sql .= 'match_result_id = ' . Sql::ProtectNumeric($i_result, true) . ",\r\n\t\t\tplayer_of_match_id = " . Sql::ProtectNumeric($player_of_match, true) . ', ' . "player_of_match_home_id = " . Sql::ProtectNumeric($player_of_match_home, true) . ', ' . "player_of_match_away_id = " . Sql::ProtectNumeric($player_of_match_away, true) . ', 
			update_search = 1,  
            date_changed = ' . gmdate('U') . ", \r\n            modified_by_id = " . Sql::ProtectNumeric(AuthenticationManager::GetUser()->GetId()) . ' ' . 'WHERE match_id = ' . Sql::ProtectNumeric($o_match->GetId());
        $this->LoggedQuery($sql);
        # Copy updated match to statistics
        require_once 'stoolball/statistics/statistics-manager.class.php';
        $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
        $statistics_manager->UpdateMatchDataInStatistics($this, $o_match->GetId());
        # Save IDs of players affected by any change
        if (count($affected_players)) {
            $statistics_manager->UpdatePlayerOfTheMatchStatistics($o_match->GetId());
            $statistics_manager->DeleteObsoleteStatistics($o_match->GetId());
            $statistics_manager->UpdatePlayerStatistics($affected_players);
        }
        unset($statistics_manager);
        # Match data has changed so notify moderator
        $this->QueueForNotification($o_match->GetId(), false);
    }
 public function OnPostback()
 {
     # If there's no id, ensure no match object is created. Page will then display a "match not found" message.
     # There's a separate page for adding matches, even for admins.
     if (!$this->editor->GetDataObjectId()) {
         return;
     }
     # Get the submitted match
     $this->match = $this->editor->GetDataObject();
     $check_match = $this->match;
     # Because this is a new request, if the user isn't admin we need to reverify whether this is the match owner
     # before letting anything happen. Can't trust that info from a postback so MUST go to the database to check it.
     if (!$this->b_user_is_match_admin) {
         $this->match_manager->ReadByMatchId(array($this->editor->GetDataObjectId()));
         $check_match = $this->match_manager->GetFirst();
         $this->b_user_is_match_owner = ($check_match instanceof Match and AuthenticationManager::GetUser()->GetId() == $check_match->GetAddedBy()->GetId());
         if ($this->b_user_is_match_owner) {
             # Set the owner of the match. This means the edit control knows who the owner is and therefore
             # whether to display the fixture editor on an invalid postback
             $this->match->SetAddedBy(AuthenticationManager::GetUser());
         } else {
             # If user is neither admin nor owner, they won't have the team info. Get it from the $check_match so
             # that the match title can be updated correctly with a changed result.
             $this->match->SetHomeTeam($check_match->GetHomeTeam());
             $this->match->SetAwayTeam($check_match->GetAwayTeam());
         }
     }
     # Don't wan't to edit tournaments on this page, so even as admin make sure we're not trying to save one.
     # If user's not admin, can't change the match type, so find out what that is from the db too. For admin,
     # $check_match is the submitted one as the match type might've been changed.
     $this->b_is_tournament = $check_match->GetMatchType() == MatchType::TOURNAMENT;
     # Check whether cancel was clicked
     if ($this->editor->CancelClicked()) {
         # If so, get the match's short URL and redirect
         $this->match_manager->ExpandMatchUrl($this->match);
         $this->Redirect($this->match->GetNavigateUrl());
     }
     # save data if valid
     if ($this->IsValid() and !$this->b_is_tournament) {
         # Check whether the user has permission to update the fixture as well as the result
         if ($this->b_user_is_match_admin or $this->b_user_is_match_owner) {
             # Get the ground name from the database. This is used when compiling an email about the updated match result.
             if ($this->match->GetGround() instanceof Ground and $this->match->GetGround()->GetId() and !$this->match->GetGround()->GetName()) {
                 require_once 'stoolball/ground-manager.class.php';
                 $ground_manager = new GroundManager($this->GetSettings(), $this->GetDataConnection());
                 $ground_manager->ReadById(array($this->match->GetGround()->GetId()));
                 if ($ground_manager->GetCount()) {
                     $this->match->SetGround($ground_manager->GetFirst());
                 }
                 unset($ground_manager);
             }
             $this->match_manager->SaveFixture($this->match);
             if ($this->b_user_is_match_admin) {
                 $this->match_manager->SaveSeasons($this->match, false);
             }
             $this->editor->SetNavigateUrl($this->match->GetEditNavigateUrl());
             # because edit URL may have changed
         }
         # Save the result
         $this->match_manager->SaveIfPlayed($this->match);
         $this->match_manager->SaveWhoWonTheToss($this->match);
         $this->match_manager->SaveWhoBattedFirst($this->match);
         # If match didn't happen or the teams aren't known yet, save and finish, otherwise go to next page
         $result = $this->match->Result()->GetResultType();
         if ($result == MatchResult::HOME_WIN_BY_FORFEIT or $result == MatchResult::AWAY_WIN_BY_FORFEIT or $result == MatchResult::CANCELLED or $result == MatchResult::POSTPONED or $check_match->GetStartTime() > gmdate('U') or $this->b_user_is_match_admin and (!$this->match->GetHomeTeamId() or !$this->match->GetAwayTeamId())) {
             # Match may have been updated so, first, send an email
             $this->match_manager->NotifyMatchModerator($this->match->GetId());
             http_response_code(303);
             $this->Redirect($this->match->GetNavigateUrl());
         } else {
             http_response_code(303);
             $this->Redirect($this->match->EditScorecardUrl());
         }
     }
 }
 protected function CreateControls()
 {
     $o_match = $this->GetDataObject();
     if (is_null($o_match)) {
         $o_match = new Match($this->GetSettings());
     }
     /* @var $o_match Match */
     /* @var $o_team Team */
     $b_got_home = !is_null($o_match->GetHomeTeam());
     $b_got_away = !is_null($o_match->GetAwayTeam());
     $b_is_new_match = !(bool) $o_match->GetId();
     $b_is_tournament_match = false;
     if ($this->i_match_type == MatchType::TOURNAMENT_MATCH) {
         $b_is_tournament_match = $this->tournament instanceof Match;
     } else {
         if ($o_match->GetMatchType() == MatchType::TOURNAMENT_MATCH and $o_match->GetTournament() instanceof Match) {
             $this->SetTournament($o_match->GetTournament());
             $this->SetMatchType($o_match->GetMatchType());
             $b_is_tournament_match = true;
         }
     }
     $o_match_outer_1 = new XhtmlElement('div');
     $o_match_outer_1->SetCssClass('MatchFixtureEdit');
     $o_match_outer_1->AddCssClass($this->GetCssClass());
     $this->SetCssClass('');
     $o_match_outer_1->SetXhtmlId($this->GetNamingPrefix());
     $o_match_outer_2 = new XhtmlElement('div');
     $o_match_box = new XhtmlElement('div');
     $this->AddControl($o_match_outer_1);
     $o_match_outer_1->AddControl($o_match_outer_2);
     $o_match_outer_2->AddControl($o_match_box);
     if ($this->GetShowHeading()) {
         $s_heading = str_replace('{0}', MatchType::Text($this->i_match_type), $this->GetHeading());
         # Add match type if required
         $o_title_inner_1 = new XhtmlElement('span', htmlentities($s_heading, ENT_QUOTES, "UTF-8", false));
         $o_title_inner_2 = new XhtmlElement('span', $o_title_inner_1);
         $o_title_inner_3 = new XhtmlElement('span', $o_title_inner_2);
         $o_match_box->AddControl(new XhtmlElement('h2', $o_title_inner_3, "medium large"));
     }
     # Offer choice of season if appropriate
     $season_count = $this->seasons->GetCount();
     if ($season_count == 1 and $this->i_match_type != MatchType::PRACTICE) {
         $o_season_id = new TextBox($this->GetNamingPrefix() . 'Season', $this->seasons->GetFirst()->GetId());
         $o_season_id->SetMode(TextBoxMode::Hidden());
         $o_match_box->AddControl($o_season_id);
     } elseif ($season_count > 1 and $this->i_match_type != MatchType::PRACTICE) {
         $o_season_id = new XhtmlSelect($this->GetNamingPrefix() . 'Season', '', $this->IsValidSubmit());
         foreach ($this->Seasons()->GetItems() as $season) {
             $o_season_id->AddControl(new XhtmlOption($season->GetCompetitionName(), $season->GetId()));
         }
         $o_match_box->AddControl(new FormPart('Competition', $o_season_id));
     }
     # Start date and time
     $match_time_known = (bool) $o_match->GetStartTime();
     if (!$match_time_known) {
         # if no date set, use specified default
         if ($this->i_default_time) {
             $o_match->SetStartTime($this->i_default_time);
             if ($b_is_tournament_match) {
                 $o_match->SetIsStartTimeKnown(false);
             }
         } else {
             # if no date set and no default, default to today at 6.30pm BST
             $i_now = gmdate('U');
             $o_match->SetStartTime(gmmktime(17, 30, 00, (int) gmdate('n', $i_now), (int) gmdate('d', $i_now), (int) gmdate('Y', $i_now)));
         }
     }
     $o_date = new DateControl($this->GetNamingPrefix() . 'Start', $o_match->GetStartTime(), $o_match->GetIsStartTimeKnown(), $this->IsValidSubmit());
     $o_date->SetShowTime(true);
     $o_date->SetRequireTime(false);
     $o_date->SetMinuteInterval(5);
     # if no date set and only one season to choose from, limit available dates to the length of that season
     if (!$match_time_known and $season_count == 1) {
         if ($this->Seasons()->GetFirst()->GetStartYear() == $this->Seasons()->GetFirst()->GetEndYear()) {
             $i_mid_season = gmmktime(0, 0, 0, 6, 30, $this->Seasons()->GetFirst()->GetStartYear());
         } else {
             $i_mid_season = gmmktime(0, 0, 0, 12, 31, $this->Seasons()->GetFirst()->GetStartYear());
         }
         $season_dates = Season::SeasonDates($i_mid_season);
         $season_start_month = gmdate('n', $season_dates[0]);
         $season_end_month = gmdate('n', $season_dates[1]);
         if ($season_start_month) {
             $o_date->SetMonthStart($season_start_month);
         }
         if ($season_end_month) {
             $o_date->SetMonthEnd($season_end_month + 1);
         }
         // TODO: need a better way to handle this, allowing overlap. Shirley has indoor matches until early April.
         $season_start_year = $this->Seasons()->GetFirst()->GetStartYear();
         $season_end_year = $this->Seasons()->GetFirst()->GetEndYear();
         if ($season_start_year) {
             $o_date->SetYearStart($season_start_year);
         }
         if ($season_end_year) {
             $o_date->SetYearEnd($season_end_year);
         }
     }
     if ($b_is_tournament_match) {
         $o_date->SetShowDate(false);
         $o_date->SetShowTime(false);
         $o_match_box->AddControl($o_date);
     } else {
         $o_date_part = new FormPart('When?', $o_date);
         $o_date_part->SetIsFieldset(true);
         $o_match_box->AddControl($o_date_part);
     }
     # Who's playing?
     if ($this->i_match_type == MatchType::PRACTICE and isset($this->context_team)) {
         $home_id = new TextBox($this->GetNamingPrefix() . 'Home', $this->context_team->GetId());
         $home_id->SetMode(TextBoxMode::Hidden());
         $away_id = new TextBox($this->GetNamingPrefix() . 'Away', $this->context_team->GetId());
         $away_id->SetMode(TextBoxMode::Hidden());
         $o_match_box->AddControl($home_id);
         $o_match_box->AddControl($away_id);
     } else {
         $o_home_list = new XhtmlSelect($this->GetNamingPrefix() . 'Home');
         $o_away_list = new XhtmlSelect($this->GetNamingPrefix() . 'Away');
         $first_real_team_index = 0;
         if ($this->b_user_is_admin) {
             # Option of not specifying teams is currently admin-only
             # Value of 0 is important because PHP sees it as boolean negative, but it can be used as the indexer of an array in JavaScript
             $o_home_list->AddControl(new XhtmlOption("Don't know yet", '0'));
             $o_away_list->AddControl(new XhtmlOption("Don't know yet", '0'));
             $first_real_team_index = 1;
         }
         foreach ($this->a_teams as $group_name => $teams) {
             foreach ($teams as $o_team) {
                 $home_option = new XhtmlOption($o_team->GetName(), $o_team->GetId());
                 if (is_string($group_name) and $group_name) {
                     $home_option->SetGroupName($group_name);
                 }
                 $o_home_list->AddControl($home_option);
                 $away_option = new XhtmlOption($o_team->GetName(), $o_team->GetId());
                 if (is_string($group_name) and $group_name) {
                     $away_option->SetGroupName($group_name);
                 }
                 $o_away_list->AddControl($away_option);
             }
         }
         $o_home_part = new FormPart('Home team', $o_home_list);
         $o_away_part = new FormPart('Away team', $o_away_list);
         $o_match_box->AddControl($o_home_part);
         $o_match_box->AddControl($o_away_part);
         if ($b_got_home) {
             $o_home_list->SelectOption($o_match->GetHomeTeamId());
         }
         if (!$b_got_home and $b_is_new_match) {
             // if no home team data, select the first team by default
             // unless editing a match, in which case it may be correct to have no teams (eg cup final)
             $o_home_list->SelectIndex($first_real_team_index);
         }
         if (!$b_got_away and $b_is_new_match) {
             // if no away team data, select the second team as the away team so that it's not the same as the first
             // unless editing a match, in which case it may be correct to have no teams (eg cup final).
             $o_away_list->SelectIndex($first_real_team_index + 1);
             // if there was a home team but not an away team, make sure we don't select the home team against itself
             if ($b_got_home and $o_away_list->GetSelectedValue() == (string) $o_match->GetHomeTeamId()) {
                 $o_away_list->SelectIndex($first_real_team_index);
             }
         } else {
             if ($b_got_away) {
                 $o_away_list->SelectOption($o_match->GetAwayTeamId());
             }
             if (!$b_is_new_match) {
                 # Note which away team was previously saved, even if it's "not known" - this is for JavaScript to know it shouldn't auto-change the away team
                 $away_saved = new TextBox($this->GetNamingPrefix() . 'SavedAway', $o_match->GetAwayTeamId());
                 $away_saved->SetMode(TextBoxMode::Hidden());
                 $o_match_box->AddControl($away_saved);
                 unset($away_saved);
             }
         }
     }
     # Where?
     # If tournament match, assume same ground as tournament. Otherwise ask the user for ground.
     if ($b_is_tournament_match) {
         $ground = new TextBox($this->GetNamingPrefix() . 'Ground', $this->tournament->GetGroundId() ? $this->tournament->GetGroundId() : $o_match->GetGroundId());
         $ground->SetMode(TextBoxMode::Hidden());
         $o_match_box->AddControl($ground);
     } else {
         $o_ground_list = new XhtmlSelect($this->GetNamingPrefix() . 'Ground');
         $o_ground_list->AddControl(new XhtmlOption("Don't know", -1));
         $o_ground_list->AddControl(new XhtmlOption('Not listed (type the address in the notes field)', -2));
         # Promote home grounds for this season to the top of the list
         $a_home_ground_ids = array();
         foreach ($this->a_teams as $teams) {
             foreach ($teams as $o_team) {
                 $a_home_ground_ids[$o_team->GetId()] = $o_team->GetGround()->GetId();
             }
         }
         $a_home_grounds = array();
         $a_other_grounds = array();
         /* @var $o_ground Ground */
         foreach ($this->a_grounds as $o_ground) {
             if (array_search($o_ground->GetId(), $a_home_ground_ids) > -1) {
                 $a_home_grounds[] = $o_ground;
             } else {
                 $a_other_grounds[] = $o_ground;
             }
         }
         # Add home grounds
         foreach ($a_home_grounds as $o_ground) {
             $option = new XhtmlOption($o_ground->GetNameAndTown(), $o_ground->GetId());
             $option->SetGroupName('Home grounds');
             $o_ground_list->AddControl($option);
         }
         # Add away grounds
         foreach ($a_other_grounds as $o_ground) {
             $option = new XhtmlOption($o_ground->GetNameAndTown(), $o_ground->GetId());
             $option->SetGroupName('Away grounds');
             $o_ground_list->AddControl($option);
         }
         # Select ground
         if ($o_match->GetGroundId()) {
             $o_ground_list->SelectOption($o_match->GetGroundId());
         } elseif ($this->i_match_type == MatchType::PRACTICE and isset($this->context_team)) {
             $o_ground_list->SelectOption($this->context_team->GetGround()->GetId());
         }
         $o_ground_part = new FormPart('Where?', $o_ground_list);
         $o_match_box->AddControl($o_ground_part);
         # Note which grounds belong to which teams, for use by match-fixture-edit-control.js to select a ground when the home team is changed
         # Format is 1,2;2,3;4,5
         # where ; separates each team, and for each team the first number identifies the team and the second is the ground
         $s_team_ground = '';
         foreach ($a_home_ground_ids as $i_team => $i_ground) {
             if ($s_team_ground) {
                 $s_team_ground .= ';';
             }
             $s_team_ground .= $i_team . ',' . $i_ground;
         }
         $o_hidden = new TextBox($this->GetNamingPrefix() . 'TeamGround', $s_team_ground);
         $o_hidden->SetMode(TextBoxMode::Hidden());
         $o_match_box->AddControl($o_hidden);
         unset($o_hidden);
         # Note which ground was previously saved - this is for JavaScript to know it shouldn't auto-change the ground
         if (!$b_is_new_match) {
             $o_hidden = new TextBox($this->GetNamingPrefix() . 'SavedGround', $o_match->GetGroundId());
             $o_hidden->SetMode(TextBoxMode::Hidden());
             $o_match_box->AddControl($o_hidden);
             unset($o_hidden);
         }
     }
     # Notes
     $o_notes = new TextBox($this->GetNamingPrefix() . 'Notes', $o_match->GetNotes());
     $o_notes->SetMode(TextBoxMode::MultiLine());
     $o_notes_part = new FormPart('Notes', $o_notes);
     $o_match_box->AddControl($o_notes_part);
     # Remember match type, tournament and short URL
     $o_type = new TextBox($this->GetNamingPrefix() . 'MatchType', $this->GetMatchType());
     $o_type->SetMode(TextBoxMode::Hidden());
     $o_match_box->AddControl($o_type);
     if ($b_is_tournament_match) {
         $tourn_box = new TextBox($this->GetNamingPrefix() . 'Tournament', $this->tournament->GetId());
         $tourn_box->SetMode(TextBoxMode::Hidden());
         $o_match_box->AddControl($tourn_box);
     }
     $o_short_url = new TextBox($this->GetNamingPrefix() . 'ShortUrl', $o_match->GetShortUrl());
     $o_short_url->SetMode(TextBoxMode::Hidden());
     $o_match_box->AddControl($o_short_url);
     # Note the context team - to be picked up by JavaScript to enable auto-changing of away team if
     # context team is not selected as home team
     if (isset($this->context_team)) {
         $context_team_box = new TextBox($this->GetNamingPrefix() . 'ContextTeam', $this->context_team->GetId());
         $context_team_box->SetMode(TextBoxMode::Hidden());
         $o_match_box->AddControl($context_team_box);
     }
 }
 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);
     }
 }
 /**
  * Gets a hash of the specified match
  *
  * @param Match $data_object
  * @return string
  */
 protected function GetDataObjectHash($data_object)
 {
     return $this->GenerateHash(array($data_object->GetId()));
 }