function OnLoadPageData()
 {
     require_once "data/process-manager.class.php";
     $this->process = new ProcessManager();
     if ($this->process->ReadyToDeleteAll()) {
         $stats = $this->GetSettings()->GetTable("PlayerMatch");
         $sql = "TRUNCATE TABLE {$stats}";
         $this->GetDataConnection()->query($sql);
     }
     $matches = $this->GetSettings()->GetTable("MatchTeam");
     $mt = $this->GetSettings()->GetTable('MatchTeam');
     $sql = "SELECT match_id, match_team_id FROM {$matches} ORDER BY match_team_id " . $this->process->GetQueryLimit();
     $result = $this->GetDataConnection()->query($sql);
     require_once "stoolball/player-manager.class.php";
     $player_manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
     require_once 'stoolball/statistics/statistics-manager.class.php';
     $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
     while ($row = $result->fetch()) {
         $affected_players = $player_manager->ReadPlayersInMatch(array($row->match_id));
         # generate player statistics from the data entered
         if (count($affected_players)) {
             $statistics_manager->UpdateBattingStatistics($affected_players, array($row->match_team_id));
             # get the match_team_id for the bowling that goes with this batting
             $sql = "SELECT match_team_id FROM {$mt}\n\t\t\t\t\t\tWHERE match_id = (SELECT match_id FROM {$mt} WHERE match_team_id = {$row->match_team_id})\n\t\t\t\t\t\tAND match_team_id != {$row->match_team_id}\n\t\t\t\t\t\tAND team_role IN (" . TeamRole::Home() . ", " . TeamRole::Away() . ")";
             $result2 = $this->GetDataConnection()->query($sql);
             $row2 = $result2->fetch();
             $bowling_match_team_id = $row2->match_team_id;
             $statistics_manager->UpdateFieldingStatistics($affected_players, array($bowling_match_team_id));
             $statistics_manager->UpdateBowlingStatistics($affected_players, array($bowling_match_team_id));
             $statistics_manager->UpdatePlayerOfTheMatchStatistics($row->match_id);
             $statistics_manager->DeleteObsoleteStatistics($row->match_id);
         }
         $this->process->OneMoreDone();
     }
 }
コード例 #2
0
 public function OnLoadPageData()
 {
     $player_manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
     $player_manager->ReadPlayersInTeam(array($this->team->GetId()));
     $this->players = $player_manager->GetItems();
     unset($player_manager);
     if (count($this->players)) {
         $this->team = $this->players[0]->Team();
     }
 }
コード例 #3
0
 public function OnLoadPageData()
 {
     # get player
     if (!is_object($this->player)) {
         $id = $this->player_manager->GetItemId($this->player);
         if ($id) {
             $this->player_manager->ReadPlayerById($id);
             $this->player = $this->player_manager->GetFirst();
         }
     }
     # tidy up
     unset($this->player_manager);
 }
 /**
  * If the player parameter is in the query string apply player filter
  * @param SiteSettings $settings
  * @param MySqlConnection $connection
  * @param StatisticsManager $statistics_manager
  */
 public static function ApplyPlayerFilter(SiteSettings $settings, MySqlConnection $connection, StatisticsManager $statistics_manager)
 {
     $filter = "";
     if (isset($_GET['player']) and is_numeric($_GET['player'])) {
         require_once 'stoolball/player-manager.class.php';
         $player_manager = new PlayerManager($settings, $connection);
         $player_manager->ReadPlayerById($_GET['player']);
         $player = $player_manager->GetFirst();
         unset($player_manager);
         if (!is_null($player)) {
             $statistics_manager->FilterByPlayer(array($player->GetId()));
             $filter = "for " . $player->GetName() . " ";
         }
     }
     return $filter;
 }
コード例 #5
0
 public function OnLoadPageData()
 {
     # Read the player data if (a) it's not a new player and (b) it's not in the postback data
     if ($this->player->GetId() and !$this->IsPostback()) {
         $this->player_manager->ReadPlayerById($this->player->GetId());
         $this->player = $this->player_manager->GetFirst();
     }
     unset($this->player_manager);
     # ensure we have a player
     if (!$this->player instanceof Player) {
         $this->Redirect();
     }
     # if it's a new player, get the team details
     if (!$this->player->GetId() or $this->add_player_already_exists) {
         if (!$this->team instanceof Team) {
             require_once "stoolball/team-manager.class.php";
             $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
             $team_manager->ReadById(array($this->player->Team()->GetId()));
             $this->team = $team_manager->GetFirst();
             unset($team_manager);
         }
         $this->player->Team()->SetName($this->team->GetName());
         $this->player->Team()->SetShortUrl($this->team->GetShortUrl());
     }
     # ensure we have permission
     $this->CheckForPermission($this->player->Team());
 }
コード例 #6
0
    public function OnLoadPageData()
    {
        # Read all the players from all specified teams
        require_once "stoolball/player-manager.class.php";
        $player_manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
        $player_manager->ReadPlayersForAutocomplete($this->team_ids);
        $players = $player_manager->GetItems();
        unset($player_manager);
        if (count($players)) {
            # Sort player names into team-by-team array
            $player_data_by_team = array();
            $team_by_player_name = array();
            foreach ($players as $player) {
                /* @var $player Player */
                # Remember the teams each name is in
                $escaped_name = str_replace("'", "\\'", Html::Encode($player->GetName()));
                # escape single quotes because this will become JS string
                if (!array_key_exists($escaped_name, $team_by_player_name)) {
                    $team_by_player_name[$escaped_name] = array();
                }
                $team_by_player_name[$escaped_name][] = $player->Team()->GetId();
                # Build up the data to display in the autocomplete dropdown
                if (!array_key_exists($player->Team()->GetId(), $player_data_by_team)) {
                    $player_data_by_team[$player->Team()->GetId()] = array();
                }
                $prompt_start = " (";
                if ($player->GetTotalMatches() == 1) {
                    $prompt_start .= "1 match";
                } else {
                    if ($player->GetTotalMatches() > 1) {
                        $prompt_start .= Html::Encode($player->GetTotalMatches() . " matches");
                    }
                }
                $prompt_team = Html::Encode(" for " . $player->Team()->GetName());
                $prompt_end = "";
                if ($player->GetFirstPlayedDate()) {
                    $first_year = gmdate("Y", $player->GetFirstPlayedDate());
                    $last_year = gmdate("Y", $player->GetLastPlayedDate());
                    $prompt_end .= " " . $first_year;
                    if ($first_year != $last_year) {
                        $prompt_end .= "–" . gmdate("y", $player->GetLastPlayedDate());
                    }
                }
                $prompt_end .= ")";
                $player_data_by_team[$player->Team()->GetId()][] = "{label:\"" . $escaped_name . "\",dates:\"" . str_replace("'", "\\'", $prompt_start . $prompt_end) . "\",team:\"" . str_replace("'", "\\'", $prompt_start . $prompt_team . $prompt_end) . "\"}";
                # escape single quotes for JS string
            }
            # Write those names as a JS array
            ?>
var stoolballAutoSuggest = (function() {

	var playersByTeam = [<?php 
            echo implode(",", $this->team_ids);
            ?>
];
	var teamsByPlayer = [];
<?php 
            foreach ($player_data_by_team as $team_id => $player_data) {
                echo "\tplayersByTeam[{$team_id}] = [" . implode(",", $player_data) . "];\n";
            }
            foreach ($team_by_player_name as $player_name => $team_ids) {
                echo "\tteamsByPlayer['{$player_name}'] = ['" . implode("','", $team_ids) . "'];\n";
            }
            ?>

	function enableSuggestions()
	{
		// find out which team(s) the player could come from
		var classes = this.className.split(" ");
		var suggestions = [];
		var showTeam = false;

		for (key in classes)
		{
			if (classes[key].match(/^team[0-9]+$/))
			{
				var players = playersByTeam[classes[key].substring(4)];
				if (typeof players == 'undefined') continue;

				if (suggestions.length > 0) showTeam = true;
				suggestions = suggestions.concat(players);
			}
		}

		// hook up the autocomplete to work with just the player's name, not their supporting info
		var input = $(this);
		if (!input.hasClass("autocomplete"))
		{
			input.autocomplete({source:suggestions}).data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append(showTeam ? "<a>" + item.label + " " + item.team + "</a>" : "<a>" + item.label + " " + item.dates + "</a>" )
					.appendTo( ul )};
			input.change(selectTeamForPlayer).blur(addPlayerSuggestion);
		}
		else
		{
			input.autocomplete("option","source",suggestions);
		}
	}

	function selectTeamForPlayer(e)
   	{
   		// first, get value from "this" while it refers to the textbox
		var playerName = $.trim(this.value);

   		// if the next control selects the player's team (ie: player of the match), try to match it automatically.
		$("select.playerTeam", this.parentNode).each(function()
		{
			// expecting "don't know", "home" and "away"
			if (this.options.length == 3)
			{
				if (playerName.length == 0)
				{
					this.options[0].selected = true;
					return;
				}

				// see if there's a matching player name
				var teams = teamsByPlayer[playerName];
				if (typeof teams == 'undefined') return;

				// are they in the available teams?
				var couldBeHome = false;
				var couldBeAway = false;
				for (key in teams)
				{
					if (teams[key] == this.options[1].value) couldBeHome = true;
					if (teams[key] == this.options[2].value) couldBeAway = true;
				}

				// select only if sure which one it is
				if (couldBeHome && !couldBeAway) this.options[1].selected = true;
				if (!couldBeHome && couldBeAway) this.options[2].selected = true;
			}
		});
   	}

   	function addPlayerSuggestion(e)
   	{
		// if box blank, no new player
		this.value = $.trim(this.value);
		if (this.value.length == 0) return;

		// Identify teams associated with this box
		var classes = this.className.split(" ");
		var teamIds = [];

		for (key in classes)
		{
			if (classes[key].match(/^team[0-9]+$/))
			{
				teamIds[teamIds.length] = classes[key].substring(4);
			}
		}

		// see if any of those teams do not currently contain this player
		for (var i = 0; i < teamIds.length; i++)
		{
			// get array of players for the team
			var players = playersByTeam[teamIds[i]];
			if (typeof players == 'undefined') players = playersByTeam[teamIds[i]] = [];

			var newPlayer = true;
			var len = players.length;
			for (var j = 0; j < len; j++)
			{
				if (players[j].label == this.value)
				{
					newPlayer = false;
					break;
				}
			}

			if (newPlayer)
			{
				// Add the new player
				playersByTeam[teamIds[i]].unshift({label: this.value, dates:" (this match)",team:" (this match)"});
				teamsByPlayer[players[j].value] = [teamIds[i]];

				// Remove and re-connect autocomplete
				$("input.player.team" + teamIds[i], "form").each(enableSuggestions);
			}
		}
   	}
   	
   	return { enablePlayerSuggestions: enableSuggestions };
})();
$(function() {
    
    // find anywhere a player's name should be entered
    $("input.player", "form").each(stoolballAutoSuggest.enablePlayerSuggestions);

});
			<?php 
        }
        exit;
    }
コード例 #7
0
 private function IndexPlayers()
 {
     require_once "data/process-manager.class.php";
     $this->process = new ProcessManager("players", 500);
     if ($this->process->ReadyToDeleteAll()) {
         $this->SearchIndexer()->DeleteFromIndexByType("player");
     }
     # Get all players, but exclude unused extras
     $player = $this->GetSettings()->GetTable('Player');
     $player_batch = $this->GetDataConnection()->query("SELECT player_id FROM {$player} WHERE total_matches >= 1 ORDER BY player_id" . $this->process->GetQueryLimit());
     $player_ids = array();
     while ($row = $player_batch->fetch()) {
         $player_ids[] = $row->player_id;
     }
     if (count($player_ids)) {
         require_once 'stoolball/player-manager.class.php';
         require_once 'search/player-search-adapter.class.php';
         $manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
         foreach ($player_ids as $player_id) {
             $manager->ReadPlayerById($player_id);
             $players = $manager->GetItems();
             foreach ($players as $player) {
                 $adapter = new PlayerSearchAdapter($player);
                 $this->SearchIndexer()->Index($adapter->GetSearchableItem());
                 $this->process->OneMoreDone();
             }
         }
         $this->SearchIndexer()->CommitChanges();
         unset($manager);
     }
 }
 /**
  * @access public
  * @return void
  * @param int[] $a_ids
  * @desc Delete from the db the Matches matching the supplied ids.
  */
 public function DeleteMatch($a_ids)
 {
     # check parameter
     if (!is_array($a_ids)) {
         die('No matches to delete');
     }
     # build query
     $delete_sql = array();
     $s_match = $this->GetSettings()->GetTable('Match');
     $s_season_match = $this->GetSettings()->GetTable('SeasonMatch');
     $s_mt = $this->GetSettings()->GetTable('MatchTeam');
     $batting = $this->GetSettings()->GetTable('Batting');
     $bowling = $this->GetSettings()->GetTable('Bowling');
     $stats = $this->GetSettings()->GetTable('PlayerMatch');
     $s_ids = join(', ', $a_ids);
     # delete batting and bowling
     $match_team_ids = array();
     $result = $this->GetDataConnection()->query("SELECT match_team_id FROM {$s_mt} WHERE match_id IN ({$s_ids})");
     while ($row = $result->fetch()) {
         $match_team_ids[] = $row->match_team_id;
     }
     $result->closeCursor();
     if (count($match_team_ids)) {
         $match_team_ids = join(",", $match_team_ids);
         $delete_sql[] = "DELETE FROM {$batting} WHERE match_team_id IN ({$match_team_ids})";
         $delete_sql[] = "DELETE FROM {$bowling} WHERE match_team_id IN ({$match_team_ids})";
     }
     $this->GetDataConnection()->query("DELETE FROM {$stats} WHERE match_id IN ({$s_ids})");
     # delete teams
     $delete_sql[] = "DELETE FROM {$s_mt} WHERE match_id IN ({$s_ids})";
     # delete seasons
     $delete_sql[] = "DELETE FROM {$s_season_match} WHERE match_id IN ({$s_ids})";
     # if this is a tournament, delete the matches
     $tournament_match_ids = array();
     $s_sql = 'SELECT match_id FROM ' . $s_match . ' WHERE tournament_match_id IN (' . $s_ids . ') ';
     $result = $this->GetDataConnection()->query($s_sql);
     while ($row = $result->fetch()) {
         $tournament_match_ids[] = $row->match_id;
     }
     $result->closeCursor();
     if (count($tournament_match_ids)) {
         $this->DeleteMatch($tournament_match_ids);
     }
     # delete comments thread
     $delete_sql[] = "DELETE FROM nsa_forum_message WHERE item_id IN ({$s_ids}) AND item_type = " . ContentType::STOOLBALL_MATCH;
     # delete match(es)
     $delete_sql[] = "DELETE FROM {$s_match} WHERE match_id IN ({$s_ids});";
     # delete from short URL cache
     require_once 'http/short-url-manager.class.php';
     $o_url_manager = new ShortUrlManager($this->GetSettings(), $this->GetDataConnection());
     $s_sql = "SELECT short_url FROM {$s_match} WHERE match_id IN ({$s_ids})";
     $result = $this->GetDataConnection()->query($s_sql);
     while ($row = $result->fetch()) {
         $o_url_manager->Delete($row->short_url);
     }
     $result->closeCursor();
     unset($o_url_manager);
     # get players involved in the match before it's deleted, so that player statistics can be updated
     require_once 'stoolball/player-manager.class.php';
     $player_manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
     $player_ids = $player_manager->ReadPlayersInMatch($a_ids);
     unset($player_manager);
     # Run the collected delete commands
     foreach ($delete_sql as $sql) {
         $this->LoggedQuery($sql);
     }
     # update player stats, removing this match and any players who featured only in this match
     require_once 'stoolball/statistics/statistics-manager.class.php';
     $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
     if (count($player_ids)) {
         $statistics_manager->UpdatePlayerStatistics($player_ids);
     }
     unset($statistics_manager);
     return $this->GetDataConnection()->GetAffectedRows();
 }
コード例 #9
0
 public function OnLoadPageData()
 {
     # Always get the player's unfiltered profile, because it's needed for the page description
     require_once "stoolball/player-manager.class.php";
     $player_manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
     $player_manager->ReadPlayerById($this->player->GetId());
     $this->player_unfiltered = $player_manager->GetFirst();
     if (!$this->player_unfiltered instanceof Player) {
         http_response_code(404);
         $this->not_found = true;
         return;
     }
     # Update search engine
     if ($this->player_unfiltered->GetSearchUpdateRequired()) {
         require_once "search/player-search-adapter.class.php";
         $this->SearchIndexer()->DeleteFromIndexById("player" . $this->player->GetId());
         $adapter = new PlayerSearchAdapter($this->player_unfiltered);
         $this->SearchIndexer()->Index($adapter->GetSearchableItem());
         $this->SearchIndexer()->CommitChanges();
         $player_manager->SearchUpdated($this->player->GetId());
     }
     unset($player_manager);
     # Check first for a player created using 'add player', who hasn't played yet
     if ($this->player_unfiltered->GetTotalMatches() == 0) {
         $this->player = $this->player_unfiltered;
     } else {
         # Now get statistics for the player
         $statistics_manager = new StatisticsManager($this->GetSettings(), $this->GetDataConnection());
         $statistics_manager->FilterByPlayer(array($this->player->GetId()));
         # Apply filters common to all statistics
         $this->filter_control = new StatisticsFilterControl();
         $filter_batting_position = StatisticsFilter::SupportBattingPositionFilter($statistics_manager);
         $this->filter_control->SupportBattingPositionFilter($filter_batting_position);
         $this->filter .= $filter_batting_position[2];
         $filter_match_type = StatisticsFilter::SupportMatchTypeFilter($statistics_manager);
         $this->filter_control->SupportMatchTypeFilter($filter_match_type);
         $this->filter .= $filter_match_type[2];
         $filter_opposition = StatisticsFilter::SupportOppositionFilter($statistics_manager);
         $this->filter_control->SupportOppositionFilter($filter_opposition);
         $this->filter .= $filter_opposition[2];
         $filter_competition = StatisticsFilter::SupportCompetitionFilter($statistics_manager);
         $this->filter_control->SupportCompetitionFilter($filter_competition);
         $this->filter .= $filter_competition[2];
         $this->filter .= StatisticsFilter::ApplySeasonFilter($this->GetSettings(), $this->GetDataConnection(), $statistics_manager);
         $filter_ground = StatisticsFilter::SupportGroundFilter($statistics_manager);
         $this->filter_control->SupportGroundFilter($filter_ground);
         $this->filter .= $filter_ground[2];
         $filter_date = StatisticsFilter::SupportDateFilter($statistics_manager);
         if (!is_null($filter_date[0])) {
             $this->filter_control->SupportAfterDateFilter($filter_date[0]);
         }
         if (!is_null($filter_date[1])) {
             $this->filter_control->SupportBeforeDateFilter($filter_date[1]);
         }
         $this->filter .= $filter_date[2];
         $filter_innings = StatisticsFilter::SupportInningsFilter($statistics_manager);
         $this->filter_control->SupportInningsFilter($filter_innings[1]);
         $this->filter .= $filter_innings[2];
         $filter_won_match = StatisticsFilter::SupportMatchResultFilter($statistics_manager);
         $this->filter_control->SupportMatchResultFilter($filter_won_match[1]);
         $this->filter .= $filter_won_match[2];
         # Now get the statistics for the player
         $data = $statistics_manager->ReadPlayerSummary();
         if (count($data)) {
             $this->player = $data[0];
         } else {
             if ($this->filter) {
                 # If no matches matched the filter, ensure we have the player's name and team
                 $this->player = $this->player_unfiltered;
                 $this->filter_matched_nothing = true;
             } else {
                 $this->regenerating = true;
             }
         }
         $data = $statistics_manager->ReadBestBattingPerformance(false);
         foreach ($data as $performance) {
             $batting = new Batting($this->player, $performance["how_out"], null, null, $performance["runs_scored"], $performance["balls_faced"]);
             $this->player->Batting()->Add($batting);
         }
         if ($this->player->GetPlayerRole() == Player::PLAYER) {
             $data = $statistics_manager->ReadBestPlayerAggregate("player_of_match");
             $this->player->SetTotalPlayerOfTheMatchNominations(count($data) ? $data[0]["statistic"] : 0);
         }
         unset($statistics_manager);
     }
 }
 /**
  * @access public
  * @return void
  * @param int[] $a_ids
  * @desc Delete from the db the Teams matching the supplied ids
  */
 public function Delete($a_ids)
 {
     # check parameter
     $this->ValidateNumericArray($a_ids);
     if (!count($a_ids)) {
         throw new Exception('No teams to delete');
     }
     $s_ids = join(', ', $a_ids);
     # Get more information on the teams
     $teams = array();
     $s_sql = "SELECT team_id, short_url, owner_role_id FROM nsa_team WHERE team_id IN ({$s_ids})";
     $result = $this->GetDataConnection()->query($s_sql);
     while ($row = $result->fetch()) {
         $team = new Team($this->GetSettings());
         $team->SetId($row->team_id);
         $team->SetShortUrl($row->short_url);
         $team->SetOwnerRoleId($row->owner_role_id);
         $teams[] = $team;
     }
     $result->closeCursor();
     # Check that current user is an admin or a team owner
     require_once "authentication/authentication-manager.class.php";
     $user = AuthenticationManager::GetUser();
     foreach ($teams as $team) {
         /* @var $team Team */
         if (!$user->Permissions()->HasPermission(PermissionType::MANAGE_TEAMS, $team->GetLinkedDataUri())) {
             throw new Exception("Unauthorised");
         }
     }
     # delete owner role
     $authentication_manager = new AuthenticationManager($this->GetSettings(), $this->GetDataConnection(), null);
     foreach ($teams as $team) {
         /* @var $team Team */
         if ($team->GetOwnerRoleId()) {
             $authentication_manager->DeleteRole($team->GetOwnerRoleId());
         }
     }
     unset($authentication_manager);
     # delete from short URL cache
     require_once 'http/short-url-manager.class.php';
     $o_url_manager = new ShortUrlManager($this->GetSettings(), $this->GetDataConnection());
     foreach ($teams as $team) {
         /* @var $team Team */
         $o_url_manager->Delete($team->GetShortUrl());
     }
     unset($o_url_manager);
     # Delete relationships to matches
     $s_match_link = $this->GetSettings()->GetTable('MatchTeam');
     $s_sql = 'DELETE FROM ' . $s_match_link . ' WHERE team_id IN (' . $s_ids . ') ';
     $this->GetDataConnection()->query($s_sql);
     # Delete relationships to competitions
     $s_season_link = $this->GetSettings()->GetTable('TeamSeason');
     $s_sql = 'DELETE FROM ' . $s_season_link . ' WHERE team_id IN (' . $s_ids . ') ';
     $this->GetDataConnection()->query($s_sql);
     # Delete players
     require_once "player-manager.class.php";
     $player_manager = new PlayerManager($this->GetSettings(), $this->GetDataConnection());
     $player_manager->ReadPlayersInTeam($a_ids);
     $players = $player_manager->GetItems();
     if (count($players)) {
         $player_ids = array();
         foreach ($players as $player) {
             $player_ids[] = $player->GetId();
         }
         $player_manager->Delete($player_ids);
     }
     unset($player_manager);
     # delete team(s)
     $s_sql = 'DELETE FROM nsa_team WHERE team_id IN (' . $s_ids . ') ';
     $this->GetDataConnection()->query($s_sql);
     return $this->GetDataConnection()->GetAffectedRows();
 }