/**
  * Creates a TeamEditPanel
  *
  * @param SiteSettings $settings
  * @param Team $team
  * @param Season[] $seasons
  * @param Match[] $matches
  */
 public function __construct(SiteSettings $settings, Team $team, $seasons, $matches)
 {
     parent::__construct($settings, " this team");
     $is_one_time_team = $team->GetTeamType() == Team::ONCE;
     if (!$is_one_time_team) {
         $this->AddLink('tell us about your team', $settings->GetUrl('TeamAdd'));
     }
     if (AuthenticationManager::GetUser()->Permissions()->HasPermission(PermissionType::MANAGE_TEAMS, $team->GetLinkedDataUri())) {
         $this->AddLink('edit this team', $team->GetEditTeamUrl());
     }
     if (AuthenticationManager::GetUser()->Permissions()->HasPermission(PermissionType::MANAGE_TEAMS)) {
         $this->AddLink('delete this team', $team->GetDeleteTeamUrl());
     }
     if (!$is_one_time_team) {
         $b_in_league = false;
         $b_in_cup = false;
         if (is_array($seasons)) {
             foreach ($seasons as $season) {
                 /* @var $season Season */
                 if (!$b_in_cup and $season->MatchTypes()->Contains(MatchType::CUP)) {
                     $b_in_cup = true;
                 }
                 if (!$b_in_league and $season->MatchTypes()->Contains(MatchType::LEAGUE)) {
                     $b_in_league = true;
                 }
                 if ($b_in_cup and $b_in_league) {
                     break;
                 }
             }
         }
         $this->AddLink('add practice', $team->GetAddMatchNavigateUrl(MatchType::PRACTICE));
         $this->AddLink('add friendly match', $team->GetAddMatchNavigateUrl(MatchType::FRIENDLY));
         $this->AddLink('add tournament', $team->GetAddMatchNavigateUrl(MatchType::TOURNAMENT));
         if ($b_in_league) {
             $this->AddLink('add league match', $team->GetAddMatchNavigateUrl(MatchType::LEAGUE));
         }
         if ($b_in_cup) {
             $this->AddLink('add cup match', $team->GetAddMatchNavigateUrl(MatchType::CUP));
         }
         if (is_array($matches) and count($matches)) {
             # Make sure there's at least one match which is not a tournament or a practice
             foreach ($matches as $o_match) {
                 /* @var $o_match Match */
                 if ($o_match->GetMatchType() == MatchType::PRACTICE or $o_match->GetMatchType() == MatchType::TOURNAMENT or $o_match->GetMatchType() == MatchType::TOURNAMENT_MATCH) {
                     continue;
                 } else {
                     $this->AddLink('update results', $team->GetResultsNavigateUrl());
                     break;
                 }
             }
             $this->AddLink('add matches to your calendar', $team->GetCalendarNavigateUrl());
         }
     }
 }
 /**
  * @return void
  * @desc Re-build from data posted by this control the data object this control is editing
  */
 function BuildPostedDataObject()
 {
     $team = new Team($this->GetSettings());
     if (isset($_POST['item'])) {
         $team->SetId($_POST['item']);
     }
     if (isset($_POST['name'])) {
         $team->SetName($_POST['name']);
     }
     $team->SetWebsiteUrl($_POST['websiteUrl']);
     $team->SetIsActive(isset($_POST['playing']));
     $team->SetIntro(ucfirst(trim($_POST['intro'])));
     $team->SetPlayingTimes($_POST['times']);
     $team->SetCost($_POST['yearCost']);
     $team->SetContact($_POST['contact']);
     $team->SetPrivateContact($_POST['private']);
     $ground = new Ground($this->GetSettings());
     $ground->SetId($_POST['ground']);
     $team->SetGround($ground);
     if (isset($_POST['team_type'])) {
         $team->SetTeamType($_POST['team_type']);
         if ($team->GetTeamType() == Team::SCHOOL_YEARS) {
             $team->SetSchoolYears(array(1 => isset($_POST['year1']), 2 => isset($_POST['year2']), 3 => isset($_POST['year3']), 4 => isset($_POST['year4']), 5 => isset($_POST['year5']), 6 => isset($_POST['year6']), 7 => isset($_POST['year7']), 8 => isset($_POST['year8']), 9 => isset($_POST['year9']), 10 => isset($_POST['year10']), 11 => isset($_POST['year11']), 12 => isset($_POST['year12'])));
         }
     }
     if ($this->is_admin) {
         $team->SetShortUrl($_POST[$this->GetNamingPrefix() . 'ShortUrl']);
         $team->SetPlayerType($_POST['playerType']);
         if (isset($_POST['club']) and is_numeric($_POST['club'])) {
             $club = new Club($this->GetSettings());
             $club->SetId($_POST['club']);
             $team->SetClub($club);
         }
     }
     $this->SetDataObject($team);
 }
 /**
  * @return int
  * @param Team $team
  * @desc Save the supplied Team to the database, and return the id
  */
 public function SaveTeam(Team $team)
 {
     # First job is to check permissions. There are several scenarios:
     # - adding regular teams requires the highest privileges
     # - adding once-only teams requires low privileges
     # - editing teams has less access for a team owner than for a site admin
     #
     # Important to check the previous team type from the database before trusting
     # the one submitted, as changing the team type changes editing privileges
     $user = AuthenticationManager::GetUser();
     $is_admin = $user->Permissions()->HasPermission(PermissionType::MANAGE_TEAMS);
     $is_team_owner = $user->Permissions()->HasPermission(PermissionType::MANAGE_TEAMS, $team->GetLinkedDataUri());
     $adding = !(bool) $team->GetId();
     $old_team = null;
     if (!$adding) {
         $this->ReadById(array($team->GetId()));
         $old_team = $this->GetFirst();
         $team->SetTeamType($this->GetPermittedTeamType($old_team->GetTeamType(), $team->GetTeamType()));
     }
     $is_once_only = $team->GetTeamType() == Team::ONCE;
     # To add a regular team we need global manage teams permission
     if ($adding and !$is_once_only and !$is_admin) {
         throw new Exception("Unauthorised");
     }
     # To edit a team we need global manage teams permission, or team owner permission
     if (!$adding and !$is_admin and !$is_team_owner) {
         throw new Exception("Unauthorised");
     }
     # Only an admin can change the short URL after the team is created
     if ($adding or $is_admin) {
         # Set up short URL manager
         # Before changing the short URL, important that $old_team has a note of the current resource URI
         require_once 'http/short-url-manager.class.php';
         $o_url_manager = new ShortUrlManager($this->GetSettings(), $this->GetDataConnection());
         $new_short_url = $o_url_manager->EnsureShortUrl($team);
     }
     # build query
     $i_club_id = !is_null($team->GetClub()) ? $team->GetClub()->GetId() : null;
     $allowed_html = array('p', 'br', 'strong', 'em', 'a[href]', 'ul', 'ol', 'li');
     $school_years = $team->GetSchoolYears();
     $school_years_sql = "year1 = " . Sql::ProtectBool(array_key_exists(1, $school_years) and $school_years[1], false, false) . ", \r\n                            year2 = " . Sql::ProtectBool(array_key_exists(2, $school_years) and $school_years[2], false, false) . ", \r\n                            year3 = " . Sql::ProtectBool(array_key_exists(3, $school_years) and $school_years[3], false, false) . ", \r\n                            year4 = " . Sql::ProtectBool(array_key_exists(4, $school_years) and $school_years[4], false, false) . ", \r\n                            year5 = " . Sql::ProtectBool(array_key_exists(5, $school_years) and $school_years[5], false, false) . ", \r\n                            year6 = " . Sql::ProtectBool(array_key_exists(6, $school_years) and $school_years[6], false, false) . ", \r\n                            year7 = " . Sql::ProtectBool(array_key_exists(7, $school_years) and $school_years[7], false, false) . ", \r\n                            year8 = " . Sql::ProtectBool(array_key_exists(8, $school_years) and $school_years[8], false, false) . ", \r\n                            year9 = " . Sql::ProtectBool(array_key_exists(9, $school_years) and $school_years[9], false, false) . ", \r\n                            year10 = " . Sql::ProtectBool(array_key_exists(10, $school_years) and $school_years[10], false, false) . ", \r\n                            year11 = " . Sql::ProtectBool(array_key_exists(11, $school_years) and $school_years[11], false, false) . ", \r\n                            year12 = " . Sql::ProtectBool(array_key_exists(12, $school_years) and $school_years[12], false, false) . ", ";
     # if no id, it's a new Team; otherwise update the Team
     if ($adding) {
         $sql = 'INSERT INTO nsa_team SET ' . "team_name = " . $this->SqlString($team->GetName()) . ", \r\n            comparable_name = " . Sql::ProtectString($this->GetDataConnection(), $team->GetComparableName(), false) . ",\r\n            club_id = " . Sql::ProtectNumeric($i_club_id, true) . ", \r\n            website = " . $this->SqlString($team->GetWebsiteUrl()) . ", " . 'ground_id = ' . Sql::ProtectNumeric($team->GetGround()->GetId(), true) . ', ' . 'active = ' . Sql::ProtectBool($team->GetIsActive()) . ", \r\n            team_type = " . Sql::ProtectNumeric($team->GetTeamType()) . ", \r\n            {$school_years_sql}\r\n            player_type_id = " . Sql::ProtectNumeric($team->GetPlayerType()) . ",\r\n            intro = " . $this->SqlHtmlString($team->GetIntro(), $allowed_html) . ",\r\n            playing_times = " . $this->SqlHtmlString($team->GetPlayingTimes(), $allowed_html) . ",  \r\n            cost = " . $this->SqlHtmlString($team->GetCost(), $allowed_html) . ", " . "contact = " . $this->SqlHtmlString($team->GetContact(), $allowed_html) . ", " . "contact_nsa = " . $this->SqlHtmlString($team->GetPrivateContact(), $allowed_html) . ", " . "short_url = " . $this->SqlString($team->GetShortUrl()) . ", \r\n            update_search = " . ($is_once_only ? "0" : "1") . ", \r\n            date_added = " . gmdate('U') . ', ' . 'date_changed = ' . gmdate('U') . ", " . "modified_by_id = " . Sql::ProtectNumeric($user->GetId());
         # run query
         $this->LoggedQuery($sql);
         # get autonumber
         $team->SetId($this->GetDataConnection()->insertID());
         # Create default extras players
         require_once "player-manager.class.php";
         $player_manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
         $player_manager->CreateExtrasPlayersForTeam($team->GetId());
         unset($player_manager);
         # Create owner role
         require_once "authentication/authentication-manager.class.php";
         require_once "authentication/role.class.php";
         $authentication_manager = new AuthenticationManager($this->GetSettings(), $this->GetDataConnection(), null);
         $role = new Role();
         $role->setRoleName("Team owner: " . $team->GetName());
         $role->Permissions()->AddPermission(PermissionType::MANAGE_TEAMS, $team->GetLinkedDataUri());
         $authentication_manager->SaveRole($role);
         $sql = "UPDATE nsa_team SET owner_role_id = " . Sql::ProtectNumeric($role->getRoleId(), false, false) . ' WHERE team_id = ' . Sql::ProtectNumeric($team->GetId());
         $this->LoggedQuery($sql);
         # If creating a once-only team, make the current user an owner
         if ($is_once_only and !$is_admin) {
             $authentication_manager->AddUserToRole($user->GetId(), $role->getRoleId());
             $authentication_manager->LoadUserPermissions();
         }
         unset($authentication_manager);
     } else {
         # Now update the team, depending on permissions
         $sql = 'UPDATE nsa_team SET ' . "website = " . $this->SqlString($team->GetWebsiteUrl()) . ", " . "intro = " . $this->SqlHtmlString($team->GetIntro(), $allowed_html) . ", " . "cost = " . $this->SqlHtmlString($team->GetCost(), $allowed_html) . ", " . "contact = " . $this->SqlHtmlString($team->GetContact(), $allowed_html) . ", " . "contact_nsa = " . $this->SqlHtmlString($team->GetPrivateContact(), $allowed_html) . ",  \r\n            update_search = " . ($is_once_only ? "0" : "1") . ",  \r\n            date_changed = " . gmdate('U') . ", \r\n            modified_by_id = " . Sql::ProtectNumeric($user->GetId()) . ' ';
         if (!$is_once_only) {
             $sql .= ", \r\n                        active = " . Sql::ProtectBool($team->GetIsActive()) . ", \r\n                        team_type = " . Sql::ProtectNumeric($team->GetTeamType()) . ",\r\n                        {$school_years_sql}\r\n                        ground_id = " . Sql::ProtectNumeric($team->GetGround()->GetId(), true) . ", \r\n                        playing_times = " . $this->SqlHtmlString($team->GetPlayingTimes(), $allowed_html);
         }
         if ($is_admin or $is_once_only) {
             $sql .= ",\r\n                        team_name = " . $this->SqlString($team->GetName());
         }
         if ($is_admin) {
             $sql .= ",\r\n                        club_id = " . Sql::ProtectNumeric($i_club_id, true) . ", \r\n                        player_type_id = " . Sql::ProtectNumeric($team->GetPlayerType()) . ", \r\n                        comparable_name = " . Sql::ProtectString($this->GetDataConnection(), $team->GetComparableName(), false) . ",\r\n                        short_url = " . $this->SqlString($team->GetShortUrl()) . " ";
         }
         $sql .= "WHERE team_id = " . Sql::ProtectNumeric($team->GetId());
         $this->LoggedQuery($sql);
         # In case team name changed, update stats table
         if ($is_admin or $is_once_only) {
             $sql = "UPDATE nsa_player_match SET team_name = " . $this->SqlString($team->GetName()) . " WHERE team_id = " . Sql::ProtectNumeric($team->GetId());
             $this->LoggedQuery($sql);
             $sql = "UPDATE nsa_player_match SET opposition_name = " . $this->SqlString($team->GetName()) . " WHERE opposition_id = " . Sql::ProtectNumeric($team->GetId());
             $this->LoggedQuery($sql);
         }
     }
     if ($adding or $is_admin) {
         # Regenerate short URLs
         if (is_object($new_short_url)) {
             $new_short_url->SetParameterValuesFromObject($team);
             $o_url_manager->Save($new_short_url);
             if (!$adding) {
                 $o_url_manager->ReplacePrefixForChildUrls(Player::GetShortUrlFormatForType($this->GetSettings()), $old_team->GetShortUrl(), $team->GetShortUrl());
                 $old_prefix = $this->SqlString($old_team->GetShortUrl() . "/%");
                 $new_prefix = $this->SqlString($team->GetShortUrl());
                 $sql = "UPDATE nsa_player_match SET\r\n                            player_url = CONCAT({$new_prefix}, RIGHT(player_url,CHAR_LENGTH(player_url)-LOCATE('/',player_url)+1))\r\n                            WHERE player_url LIKE {$old_prefix}";
                 $this->LoggedQuery($sql);
             }
         }
         unset($o_url_manager);
         # Owner permission is based on the resource URI, which in turn is based on short URL,
         # so if it's changed update the permissions
         if ($old_team instanceof Team) {
             $old_resource_uri = $old_team->GetLinkedDataUri();
             $new_resource_uri = $team->GetLinkedDataUri();
             if ($old_resource_uri != $new_resource_uri) {
                 $permissions_table = $this->GetSettings()->GetTable("PermissionRoleLink");
                 $sql = "UPDATE {$permissions_table} SET resource_uri = " . $this->SqlString($new_resource_uri) . " WHERE resource_uri = " . $this->SqlString($old_resource_uri);
                 $this->LoggedQuery($sql);
             }
         }
     }
     if (!$is_once_only) {
         # Request search update for affected  competitions
         $sql = "UPDATE nsa_competition SET update_search = 1 WHERE competition_id IN \r\n                (\r\n                    SELECT competition_id FROM nsa_season WHERE season_id IN\r\n                    (\r\n                        SELECT season_id FROM nsa_team_season WHERE team_id = " . SQL::ProtectNumeric($team->GetId(), false) . " \r\n                    )\r\n                )";
         $this->LoggedQuery($sql);
         # Request searched update for effects of changing the team name
         $sql = "UPDATE nsa_player SET update_search = 1 WHERE team_id = " . SQL::ProtectNumeric($team->GetId(), false);
         $this->LoggedQuery($sql);
         $sql = "UPDATE nsa_match SET update_search = 1 WHERE match_id IN ( SELECT match_id FROM nsa_match_team WHERE team_id = " . SQL::ProtectNumeric($team->GetId(), false) . ")";
         $this->LoggedQuery($sql);
         # Request search update for changing the team home ground
         $sql = "UPDATE nsa_ground SET update_search = 1 WHERE ground_id = " . Sql::ProtectNumeric($team->GetGround()->GetId(), false);
         $this->LoggedQuery($sql);
     }
     return $team->GetId();
 }
 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);
 }