/**
  * @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();
 }