From 4a64c354ae87155cb56f579217298826f495a642 Mon Sep 17 00:00:00 2001
From: Dmitry Kutin <43126261+dkutin@users.noreply.github.com>
Date: Wed, 29 Apr 2020 22:29:11 -0400
Subject: [PATCH] Restructure files, update to work with database (#24) (#25)
---
.gitignore | 13 +-
.gitmodules | 3 -
Analytics.php | 154 ---------------------
Mail.php | 58 --------
ServiceCall.php | 103 --------------
constants.php | 39 ------
helper.php | 35 -----
lib/.gitkeep | 0
lib/PHPMailer | 1 -
pi.php | 20 ---
src/class/Analytics.php | 141 +++++++++++++++++++
src/class/Database.php | 72 ++++++++++
FantasyAPI.php => src/class/FantasyAPI.php | 64 ++++-----
src/class/ServiceCall.php | 108 +++++++++++++++
src/dbhelper.php | 94 +++++++++++++
src/generateJSON.php | 13 ++
src/helper.php | 152 ++++++++++++++++++++
src/updateDatabase.php | 22 +++
tmp/.gitkeep | 0
tmp/auth/.gitkeep | 0
tmp/data/.gitkeep | 0
tmp/data/players/.gitkeep | 0
22 files changed, 636 insertions(+), 456 deletions(-)
delete mode 100644 .gitmodules
delete mode 100644 Analytics.php
delete mode 100644 Mail.php
delete mode 100644 ServiceCall.php
delete mode 100644 constants.php
delete mode 100644 helper.php
delete mode 100644 lib/.gitkeep
delete mode 160000 lib/PHPMailer
delete mode 100644 pi.php
create mode 100644 src/class/Analytics.php
create mode 100644 src/class/Database.php
rename FantasyAPI.php => src/class/FantasyAPI.php (66%)
create mode 100644 src/class/ServiceCall.php
create mode 100644 src/dbhelper.php
create mode 100644 src/generateJSON.php
create mode 100644 src/helper.php
create mode 100644 src/updateDatabase.php
delete mode 100644 tmp/.gitkeep
delete mode 100644 tmp/auth/.gitkeep
delete mode 100644 tmp/data/.gitkeep
delete mode 100644 tmp/data/players/.gitkeep
diff --git a/.gitignore b/.gitignore
index ff8b567..a1b3cdd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,9 @@
+# Files
.DS_Store
+*.zip
+*.tar.gz
+
+# Folders
.idea/
bin/
-bin/team/
-tmp/
-tmp/auth/
-tmp/data/
-tmp/data/players/
-constants.php
-*.tar.gz
+
diff --git a/.gitmodules b/.gitmodules
deleted file mode 100644
index de3ddf6..0000000
--- a/.gitmodules
+++ /dev/null
@@ -1,3 +0,0 @@
-[submodule "lib/PHPMailer"]
- path = lib/PHPMailer
- url = https://github.com/PHPMailer/PHPMailer.git
diff --git a/Analytics.php b/Analytics.php
deleted file mode 100644
index 5807322..0000000
--- a/Analytics.php
+++ /dev/null
@@ -1,154 +0,0 @@
-player_stats = [
- 'Roster' => $this->createPlayerStats('Roster'),
- 'FA' => $this->createPlayerStats('FA'),
- ];
- }
- return $this;
- }
-
- /**
- * @return array
- */
- function generateSuggestion()
- {
- $player_delta = [
- 'FA' => [
- ONE_WEEK_AVG => $this->getPlayerDelta('FA', ONE_WEEK_AVG),
- TWO_WEEK_AVG => $this->getPlayerDelta('FA', TWO_WEEK_AVG),
- ONE_MO_AVG => $this->getPlayerDelta('FA', ONE_MO_AVG),
- ],
- 'Roster' => [
- ONE_WEEK_AVG => $this->getPlayerDelta('Roster', ONE_WEEK_AVG),
- TWO_WEEK_AVG => $this->getPlayerDelta('Roster', TWO_WEEK_AVG),
- ONE_MO_AVG => $this->getPlayerDelta('Roster', ONE_MO_AVG),
- ],
- ];
-
- $player_score = [];
-
- // TODO: Maybe use central limit theorem here to better rank players
- foreach ($player_delta as $type => $data) {
- foreach ($data as $stat => $week_values) {
- foreach ($week_values as $week => $player_averages) {
- foreach ($player_averages as $player => $delta) {
- if (empty($player_score[$type][$player])) {
- $player_score[$type][$player] = $this->player_stats[$type][$week][$player];
- }
- switch ($stat) {
- case ONE_WEEK_AVG:
- $player_score[$type][$player] += 1 * $delta;
- break;
- case TWO_WEEK_AVG:
- $player_score[$type][$player] += 1.5 * $delta;
- break;
- case ONE_MO_AVG:
- $player_score[$type][$player] += 3 * $delta;
- break;
- }
- }
- }
- }
- }
-
- $player_suggestions = [];
- foreach ($player_score['FA'] as $fa_player => $fa_score) {
- foreach ($player_score['Roster'] as $r_player => $r_score) {
- if ($fa_score > $r_score) {
- $player_suggestions[$r_player][$fa_player] = $fa_score - $r_score;
- }
- }
- }
-
- return $player_suggestions;
- }
-
- /**
- * @param $type
- * @param string $player
- * @return array
- */
- function createPlayerStats($type, $player = '') {
- global $scored_stats;
- // If we've specified a player, get their weekly stats (if available)
- if (empty($player)) {
- $files = glob(TMP_DATA_PLAYERS_DIR . "${type}/*.json", GLOB_BRACE);
- } else {
- $files = glob(TMP_DATA_PLAYERS_DIR . "${type}/player_${player}_week_*.json", GLOB_BRACE);
- if (count($files) == 0) {
- print "Not enough data given for player ${player}!";
- return [];
- }
- }
-
- $players = [];
- foreach ($files as $file) {
- $week = substr($file, -7, 2);
- $data = getContents($file);
- $gp = $data['player']['player_stats']['stats']['stat']['0']['value'];
- $averages = [];
- if ($gp > 0) {
- foreach ($data['player']['player_stats']['stats']['stat'] as $stat) {
- if (array_key_exists($stat['stat_id'], $scored_stats)) {
- $averages[$stat['stat_id']] = ((float)$scored_stats[$stat['stat_id']] * (float)$stat['value']) / (float)$gp;
- }
- }
- }
- $players[$week][$data['player']['name']['full']] = array_sum($averages);
- }
-
- return $players;
- }
-
- function getPlayerDelta($type, $stat, $player = '') {
- if (empty($this->player_stats[$type])) {
- $this->player_stats[$type] = $this->createPlayerStats($type, $player);
- }
- $data = $this->player_stats[$type];
- $stats = [];
- foreach ($data as $week => $players) {
- foreach ($players as $player => $value) {
- if (!empty($data[$week-$stat][$player])) {
- $stats[$week][$player] = $data[$week][$player] - $data[$week-$stat][$player];
- }
- }
- }
- return $stats;
- }
-
- function generateReport() {
- $suggestions = $this->generateSuggestion();
- $data = '';
- foreach ($suggestions as $r_player => $fa_players) {
- arsort($fa_players);
- $data .= "
$r_player can be replaced by:
";
- foreach ($fa_players as $fa_player => $diff) {
- $data .= "
$fa_player: $diff
";
- }
- $data .= "
";
- }
- writeToFile($data, BIN_DIR . 'analysis.csv');
- return $data;
- }
-}
diff --git a/Mail.php b/Mail.php
deleted file mode 100644
index f639c48..0000000
--- a/Mail.php
+++ /dev/null
@@ -1,58 +0,0 @@
-username = FANTASY_TRACKER_EMAIL;
- $this->password = FANTASY_TRACKER_PASSWORD;
- }
-
- function initializeMail()
- {
- $mail = new PHPMailer();
-
- // SMTP Settings
- $mail->isSMTP();
- $mail->SMTPDebug = 0;
- $mail->SMTPAuth = TRUE;
- $mail->SMTPSecure = 'tls';
- $mail->SMTPAuth = true;
- $mail->Host= 'smtp.gmail.com';
- $mail->Port = 587;
- // AUTH Settings
- $mail->Username = $this->username;
- $mail->Password = $this->password;
- // Subject and Sender
- $mail->SetFrom($this->username, "Fantasy Tracker");
- $mail->Subject = "Your Fantasy Tracker Update!";
- $this->mail = $mail;
- }
-
- function sendEmail($recipient, $data)
- {
- // Add Recipient Address
- $this->mail->addAddress($recipient);
- // Add body content
- $this->mail->isHTML(TRUE);
- $this->mail->msgHTML($data);
-
- return $this->mail->send();
- }
-}
diff --git a/ServiceCall.php b/ServiceCall.php
deleted file mode 100644
index 9c673c5..0000000
--- a/ServiceCall.php
+++ /dev/null
@@ -1,103 +0,0 @@
-api = new FantasyAPI();
- if (empty($this->week)) {
- $this->getCurrentWeek();
- }
- return $this;
- }
-
- /**
- * @return FantasyAPI
- */
- function getFantasyAPI() {
- return $this->api;
- }
-
- /**
- * @return mixed
- */
- function getCurrentWeek() {
- $current_week = "https://fantasysports.yahooapis.com/fantasy/v2/team/". LEAGUE_KEY . ".t.". TEAM_ID ."/roster";
- $answer = $this->api->makeAPIRequest($current_week)['team']['roster_adds']['coverage_value'];
- $this->week = $answer;
- return $answer;
- }
-
- /**
- * @return bool|mixed
- */
- function getMyPlayers() {
- $my_team = "https://fantasysports.yahooapis.com/fantasy/v2/team/". LEAGUE_KEY . ".t.". TEAM_ID ."/roster";
- $answer = $this->api->makeAPIRequest($my_team);
- writeToFile(json_encode($answer), TMP_DATA_DIR . LEAGUE_KEY . '_my_team.json');
- return $answer;
- }
-
- /**
- * @return array
- */
- function getFreeAgents() {
- $answer = [];
- for ($num =0; $num <= FREE_AGENTS_MAX; $num +=25) {
- $free_agents = "https://fantasysports.yahooapis.com/fantasy/v2/league/". LEAGUE_KEY ."/players;status=FA;start=${num};sort=OR";
- $answer = array_merge_recursive($answer, $this->api->makeAPIRequest($free_agents));
- }
- writeToFile(json_encode($answer), TMP_DATA_DIR . LEAGUE_KEY . '_free_agents.json');
- return $answer;
- }
-
- /**
- * @param $player_key
- * @param $type
- * @return bool|mixed
- */
- function getPlayerStats($player_key, $type) {
- $week = $this->week;
- $player = "https://fantasysports.yahooapis.com/fantasy/v2/player/395.p.${player_key}/stats";
- $answer = $this->api->makeAPIRequest($player);
- writeToFile(json_encode($answer), TMP_DATA_PLAYERS_DIR . "${type}/player_${player_key}_week_${week}.json");
- return $answer;
- }
-
- /**
- *
- */
- function getFreeAgentsStats() {
- foreach ($this->getFreeAgents()['league']['players']['player'] as $player) {
- $this->getPlayerStats($player['player_id'], 'FA');
- }
- }
-
- /**
- *
- */
- function getRosterStats() {
- foreach ($this->getMyPlayers()['team']['roster']['players']['player'] as $player) {
- $this->getPlayerStats($player['player_id'], 'Roster');
- }
- }
-}
diff --git a/constants.php b/constants.php
deleted file mode 100644
index 1c64556..0000000
--- a/constants.php
+++ /dev/null
@@ -1,39 +0,0 @@
- 1, //PTS
- '15' => 1.2, //REB
- '16' => 1.5, //AST
- '17' => 3, //BLK
- '18' => 3, //STL
- '19' => -1, //TO
-];
-
-/*
- * Non-Configurable Constants
- */
-define('AUTH_ENDPOINT', 'https://api.login.yahoo.com/oauth2/get_token');
-
-// Define Directories for referencing
-define('BIN_DIR', __DIR__ . '/bin/');
-define('TMP_DIR', __DIR__ . '/tmp/');
-define('TMP_AUTH_DIR', __DIR__ . '/tmp/auth/');
-define('TMP_DATA_DIR', __DIR__ . '/tmp/data/');
-define('TMP_DATA_PLAYERS_DIR', __DIR__ . '/tmp/data/players/');
-
-// Define Stat Types
-define('ONE_WEEK_AVG', 1);
-define('TWO_WEEK_AVG', 2);
-define('ONE_MO_AVG', 4);
-
diff --git a/helper.php b/helper.php
deleted file mode 100644
index 2128c21..0000000
--- a/helper.php
+++ /dev/null
@@ -1,35 +0,0 @@
-getRosterStats();
-$request->getFreeAgentsStats();
-// Then we generate the report
-$data = $analytics->generateReport();
-
-// Initialize mailer credentials and send email from generated CSV
-$mailer->initializeMail();
-$status = $mailer->sendEmail('', $data);
-
diff --git a/src/class/Analytics.php b/src/class/Analytics.php
new file mode 100644
index 0000000..af5f83b
--- /dev/null
+++ b/src/class/Analytics.php
@@ -0,0 +1,141 @@
+uid = $uid;
+ $this->players = [
+ 'Roster' => $this->getRoster(),
+ 'FreeAgents' => $this->getFreeAgents(),
+ ];
+ return $this;
+ }
+
+ function getRoster() {
+ $league = getUserLeague($this->uid);
+ $roster = getRoster($league['league_id'], $league['team_id']);
+ return unserialize($roster['players']);
+ }
+
+ function getFreeAgents() {
+ $league = getUserLeague($this->uid);
+ $freeagents = getFreeAgents($league['league_id']);
+ return unserialize($freeagents['players']);
+ }
+
+ function getStats($players) {
+ $player_data = [];
+ foreach ($players as $player) {
+ $player_data[$player] = getPlayerStats($player);
+ }
+ return $player_data;
+ }
+
+ function getScoredStats() {
+ $league = getUserLeague($this->uid);
+ $scored_stats = getScoredStats($league['league_id']);
+ return unserialize($scored_stats['scored_stats']);
+ }
+
+ function createPlayerStats() {
+ $stats = [];
+ $this->stats = [];
+ foreach ($this->players as $type => $players) {
+ $stats[$type] = $this->getStats($players);
+ }
+ foreach ($stats as $type => $players) {
+ foreach ($players as $index => $values) {
+ if (!empty($values)) {
+ $this->stats[$index] = $values;
+ }
+ }
+ }
+ return $this->stats;
+ }
+
+ function getPlayerDelta($player_data) {
+ $player_delta = [];
+ foreach ($player_data as $player_id => $data) {
+ $num_weeks = sizeof($data);
+ if ($num_weeks > ONE_MO_AVG && !empty($data[$num_weeks - 1]) && !empty($data[$num_weeks - 5])) {
+ foreach($data[$num_weeks - 1] as $key => $value) {
+ if ($key != 'week') {
+ $player_delta[$player_id][ONE_MO_AVG][$key] = $value - $data[$num_weeks - 5][$key];
+ }
+ }
+ }
+ if ($num_weeks > TWO_WEEK_AVG && !empty($data[$num_weeks - 1]) && !empty($data[$num_weeks - 3])) {
+ foreach($data[$num_weeks - 1] as $key => $value) {
+ if ($key != 'week') {
+ $player_delta[$player_id][TWO_WEEK_AVG][$key] = $value - $data[$num_weeks - 3][$key];
+ }
+ }
+ }
+ if ($num_weeks > ONE_WEEK_AVG && !empty($data[$num_weeks - 1]) && !empty($data[$num_weeks - 2])) {
+ foreach($data[$num_weeks - 1] as $key => $value) {
+ if ($key != 'week') {
+ $player_delta[$player_id][ONE_WEEK_AVG][$key] = $value - $data[$num_weeks - 2][$key];
+ }
+ }
+ }
+
+ }
+ return $player_delta;
+ }
+
+
+ /**
+ * @return array
+ */
+ function generateSuggestion()
+ {
+ $player_stats = $this->createPlayerStats();
+ $player_delta = $this->getPlayerDelta($player_stats);
+ $scored_stats = formatStats($this->getScoredStats());
+ $player_score = [];
+
+ // TODO: Maybe use central limit theorem here to better rank players
+ foreach ($player_delta as $player_id => $data) {
+ foreach ($data as $type => $values) {
+ if ($values['gp'] == 0) {
+ $player_score[$player_id][$type] = 0;
+ break;
+ }
+ $player_score[$player_id][$type] = 0;
+ foreach ($scored_stats as $stat_id => $value) {
+ $player_score[$player_id][$type] += $value * $values[$stat_id];
+ }
+ $player_score[$player_id][$type] = ($player_score[$player_id][$type]) / $values['gp'];
+ }
+ }
+
+ return $player_score;
+ }
+
+ function generateReport() {
+ $suggestions = $this->generateSuggestion();
+ $data = $suggestions;
+ setAnalysis($this->uid, json_encode($data));
+ return $data;
+ }
+}
diff --git a/src/class/Database.php b/src/class/Database.php
new file mode 100644
index 0000000..1b649dd
--- /dev/null
+++ b/src/class/Database.php
@@ -0,0 +1,72 @@
+server, $this->username, $this->password, $this->dbname);
+ if ($conn->connect_error) {
+ print_r($conn->connect_error);
+ return FALSE;
+ }
+
+ if ($conn->query($string) === TRUE) {
+ $conn->close();
+ return TRUE;
+ }
+ print_r($conn->error);
+ $conn->close();
+ return FALSE;
+
+ }
+
+ function get($string) {
+ $return = [];
+ $conn = new mysqli($this->server, $this->username, $this->password, $this->dbname);
+ if ($conn->connect_error) {
+ print_r($conn->connect_error);
+ return FALSE;
+ }
+ $result = $conn->query($string);
+ if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ foreach ($row as $key => $value) {
+ $return[$key] = $value;
+ }
+ }
+ }
+ $conn->close();
+ return $return;
+ }
+
+ function getMultiple($string) {
+ $return = [];
+ $row_num = 0;
+ $conn = new mysqli($this->server, $this->username, $this->password, $this->dbname);
+ if ($conn->connect_error) {
+ print_r($conn->connect_error);
+ return FALSE;
+ }
+ $result = $conn->query($string);
+ if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ foreach ($row as $key => $value) {
+ $return[$row_num][$key] = $value;
+ }
+ $row_num++;
+ }
+ }
+ $conn->close();
+ return $return;
+ }
+}
diff --git a/FantasyAPI.php b/src/class/FantasyAPI.php
similarity index 66%
rename from FantasyAPI.php
rename to src/class/FantasyAPI.php
index 5299ee5..d5c1902 100644
--- a/FantasyAPI.php
+++ b/src/class/FantasyAPI.php
@@ -1,7 +1,6 @@
auth_json_file = TMP_AUTH_DIR . 'auth_credentials_' . CONSUMER_KEY . '.json';
- if (file_exists($this->auth_json_file)) {
- $this->credentials = json_decode(file_get_contents($this->auth_json_file), TRUE);
- } else {
- $this->credentials = $this->initializeToken();
- }
- $this->credentials['expiry_time'] = filemtime($this->auth_json_file) + 3600;
-
- return $this;
+ $this->uid = $uid;
}
/**
@@ -40,11 +28,12 @@ function __construct()
*/
function makeAPIRequest($url)
{
+ $auth = getTokenCred($this->uid);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
- CURLOPT_HTTPHEADER => array('authorization: Bearer ' . $this->credentials['access_token'],
+ CURLOPT_HTTPHEADER => array('authorization: Bearer ' . $auth['access_token'],
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Cache-Control: no-cache',
@@ -77,12 +66,14 @@ function makeAPIRequest($url)
function refreshToken()
{
// If our auth file doesn't exist, make one
- if (!file_exists($this->auth_json_file)) {
+ if (!$auth = getTokenCred($this->uid)) {
$this->initializeToken();
}
-
+ if(!$cred = getUserCred($this->uid)) {
+ print 'User Consumer key and secret not init';
+ }
// If our token has not expired yet, return the existing auth
- if ($this->credentials['expiry_time'] > time()) {
+ if ($auth['expires'] > time()) {
return TRUE;
}
@@ -90,14 +81,14 @@ function refreshToken()
$post_values = [
"redirect_uri" => "oob",
"grant_type" => "refresh_token",
- "refresh_token" => $this->credentials['refresh_token']
+ "refresh_token" => $auth['refresh_token']
];
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_URL => AUTH_ENDPOINT,
+ CURLOPT_URL => 'https://api.login.yahoo.com/oauth2/get_token',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
- 'Authorization: Basic ' . base64_encode(CONSUMER_KEY . ":" . CONSUMER_SECRET),
+ 'Authorization: Basic ' . base64_encode($cred['consumer_key'] . ":" . $cred['consumer_secret']),
'Content-Type: application/x-www-form-urlencoded',
),
CURLOPT_POSTFIELDS => http_build_query($post_values)
@@ -108,29 +99,30 @@ function refreshToken()
print "Error getting Refresh Token";
return FALSE;
}
- writeToFile($resp, $this->auth_json_file);
- $this->credentials = json_decode($resp, TRUE);
- $this->credentials['expiry_time'] = time() + 3600;
+ $data = json_decode($resp, TRUE);
+ $data['expires'] = time() + $data['expires_in'];
+ updateTokenCred($this->uid, $data['access_token'], $data['refresh_token'], $data['expires'], $data['xoauth_yahoo_guid']);
return TRUE;
}
function initializeToken()
{
- $auth_code = readline('Go to: https://api.login.yahoo.com/oauth2/request_auth?client_id=' . CONSUMER_KEY . '&redirect_uri=oob&response_type=code&language=en-us and copy the code: ');
+ $user = getUserCred($this->uid);
+ $auth_code = readline('Go to: https://api.login.yahoo.com/oauth2/request_auth?client_id=' . $user['consumer_key'] . '&redirect_uri=oob&response_type=code&language=en-us and copy the code: ');
$ch = curl_init();
$post_values = [
- "client_id" => CONSUMER_KEY,
- "client_secret" => CONSUMER_SECRET,
+ "client_id" => $user['consumer_key'],
+ "client_secret" => $user['consumer_secret'],
"redirect_uri" => "oob",
"code" => $auth_code,
"grant_type" => "authorization_code"
];
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_URL => AUTH_ENDPOINT,
+ CURLOPT_URL => 'https://api.login.yahoo.com/oauth2/get_token',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
- 'Authorization: Basic ' . base64_encode(CONSUMER_KEY . ":" . CONSUMER_SECRET),
+ 'Authorization: Basic ' . base64_encode($user['consumer_key']. ":" . $user['consumer_secret']),
'Content-Type: application/x-www-form-urlencoded',
),
CURLOPT_POSTFIELDS => http_build_query($post_values)
@@ -141,9 +133,9 @@ function initializeToken()
print 'Error Initializing Token';
return FALSE;
}
- writeToFile($resp, $this->auth_json_file);
- $this->credentials = json_decode($resp, TRUE);
- $this->credentials['expiry_time'] = time() + 3600;
+ $data = json_decode($resp, TRUE);
+ $data['expires'] = time() + $data['expires_in'];
+ setTokenCred($data['access_token'], $data['refresh_token'], $data['expires'], $data['xoauth_yahoo_guid']);
return TRUE;
}
}
diff --git a/src/class/ServiceCall.php b/src/class/ServiceCall.php
new file mode 100644
index 0000000..beea378
--- /dev/null
+++ b/src/class/ServiceCall.php
@@ -0,0 +1,108 @@
+uid = $uid;
+ $this->api = new FantasyAPI($uid);
+ if (empty($this->week)) {
+ $this->getCurrentWeek();
+ }
+ return $this;
+ }
+
+ /**
+ * @return FantasyAPI
+ */
+ function getFantasyAPI() {
+ return $this->api;
+ }
+
+ /**
+ * @return mixed
+ */
+ function getCurrentWeek() {
+ if (!$data = getUserLeague($this->uid)) return FALSE;
+ $current_week = "https://fantasysports.yahooapis.com/fantasy/v2/team/". $data['league_id'] . ".t.". $data['team_id'] ."/roster";
+ $this->week = $this->api->makeAPIRequest($current_week)['team']['roster_adds']['coverage_value'];
+ return $this->week;
+ }
+
+ function getOwnedPlayers() {
+ if (!$league = getUserLeague($this->uid)) return FALSE;
+ if (!$num_teams = getNumTeams($league['league_id'])) return FALSE;
+ $owned = [];
+ for ($i = 1; $i <= $num_teams['num_teams']; $i++) {
+ $team = "https://fantasysports.yahooapis.com/fantasy/v2/team/". $league['league_id'] . ".t.". $i ."/roster";
+ $answer = $this->api->makeAPIRequest($team);
+ $players = formatRoster($answer);
+ $owned[$i] = $players;
+ $player_info = formatOwnedPlayerInfo($answer);
+ foreach ($player_info as $player_id => $values) {
+ updatePlayerInfo($player_id, $values);
+ }
+ updateRoster($league['league_id'], $i, serialize($players));
+ }
+ return $owned;
+ }
+
+
+ /**
+ * @return array | boolean
+ */
+ function getFreeAgents() {
+ if (!$data = getUserLeague($this->uid)) return FALSE;
+ $answer = [];
+ for ($num = 0; $num <= 50; $num +=25) {
+ $free_agents = "https://fantasysports.yahooapis.com/fantasy/v2/league/${data['league_id']}/players;status=FA;start=${num};sort=OR";
+ $answer = array_merge_recursive($answer, $this->api->makeAPIRequest($free_agents));
+ }
+ $players = formatFreeAgents($answer);
+ $player_info = formatFreeAgentInfo($answer);
+ foreach ($player_info as $player_id => $values) {
+ updatePlayerInfo($player_id, $values);
+ }
+ updateFreeAgents($data['league_id'], serialize($players));
+ return $players;
+ }
+
+ /**
+ * @param $player_id
+ * @return bool|mixed
+ */
+ function getPlayerStats($player_id) {
+ if (!$data = getUserLeague($this->uid)) return FALSE;
+ $player = "https://fantasysports.yahooapis.com/fantasy/v2/player/395.p.${player_id}/stats";
+ $answer = $this->api->makeAPIRequest($player);
+ $scored_stats = unserialize(getScoredStats($data['league_id'])['scored_stats']);
+ $data = formatPlayerStats($answer, $scored_stats);
+ updatePlayerStats($player_id, $this->week, $data);
+ return $data;
+ }
+}
diff --git a/src/dbhelper.php b/src/dbhelper.php
new file mode 100644
index 0000000..9dbe09a
--- /dev/null
+++ b/src/dbhelper.php
@@ -0,0 +1,94 @@
+get("SELECT consumer_key, consumer_secret FROM `user` WHERE id = '${uid}'");;
+}
+
+function getTokenCred($uid) {
+ global $db;
+ return $db->get("SELECT access_token, refresh_token, expires, xoauth_yahoo_guid FROM auth WHERE user_id = '${uid}'");;
+}
+
+function setTokenCred($access_token, $refresh_token, $expires, $xoauth_yahoo_guid) {
+ global $db;
+ return $db->put("INSERT IGNORE INTO auth (access_token, refresh_token, expires, xoauth_yahoo_guid) VALUES ('${access_token}', '${refresh_token}', '${expires}', '${xoauth_yahoo_guid}')");
+}
+
+function updateTokenCred($uid, $access_token, $refresh_token, $expires, $xoauth_yahoo_guid) {
+ global $db;
+ return $db->put("UPDATE auth SET access_token = '${access_token}', refresh_token = '${refresh_token}', expires = '${expires}', xoauth_yahoo_guid = '${xoauth_yahoo_guid}' WHERE user_id = '${uid}'");
+}
+
+function getUserLeague($uid) {
+ global $db;
+ return $db->get("SELECT league_id, team_id FROM `user` WHERE id = '${uid}'");
+}
+
+function getNumTeams($league_id) {
+ global $db;
+ return $db->get("SELECT num_teams FROM league WHERE id = '${league_id}'");
+}
+
+function setAuth($data) {
+ global $db;
+ $db->put("INSERT IGNORE INTO `user` (league_id, team_id, consumer_key, consumer_secret) VALUES ()");
+}
+
+function updateRoster($league_id, $team_id, $players) {
+ global $db;
+ $db->put("INSERT INTO team (league_id, team_id, players) VALUES ('${league_id}', '${team_id}', '${players}') ON DUPLICATE KEY UPDATE players = '${players}'");
+}
+
+function updateFreeAgents($league_id, $players) {
+ global $db;
+ $db->put("INSERT INTO freeagents (league_id, players) VALUES ('${league_id}', '${players}') ON DUPLICATE KEY UPDATE players = '${players}'");
+}
+
+function getFreeAgents($league_id) {
+ global $db;
+ return $db->get("SELECT players FROM freeagents WHERE league_id = '${league_id}'");
+}
+function updatePlayerStats($player_id, $week, $stats) {
+ global $db;
+ $db->put("INSERT INTO player_data (player_id, week, gp, pts, ast, reb, stl, blk, trn) VALUES ('${player_id}', '${week}', '${stats['gp']}', '${stats['pts']}', '${stats['ast']}', '${stats['reb']}', '${stats['stl']}', '${stats['blk']}', '${stats['trn']}') ON DUPLICATE KEY UPDATE gp = '${stats['gp']}', pts = '${stats['pts']}', ast = '${stats['ast']}', reb = '${stats['reb']}', stl = '${stats['stl']}', blk = '${stats['blk']}', trn = '${stats['trn']}'");
+}
+
+function getPlayerStats($player_id) {
+ global $db;
+ return $db->getMultiple("SELECT week, gp, pts, ast, reb, stl, blk, trn FROM player_data WHERE player_id = '${player_id}'");
+}
+
+function getPlayerInfo($player_id) {
+ global $db;
+ return $db->getMultiple("SELECT * FROM player WHERE player_id = '${player_id}'");
+}
+
+function getScoredStats($league_id) {
+ global $db;
+ return $db->get("SELECT scored_stats FROM league WHERE id = '${league_id}'");
+}
+
+function setScoredStats($league_id, $scored_stats) {
+ global $db;
+ $db->put("UPDATE league SET scored_stats = '${scored_stats}' WHERE id='${league_id}'");
+}
+
+function getRoster($league_id, $team_id) {
+ global $db;
+ return $db->get("SELECT players FROM team WHERE league_id = '${league_id}' AND team_id = '${team_id}'");
+}
+
+function setAnalysis($uid, $data) {
+ global $db;
+ $db->put("INSERT INTO analysis VALUES (NULL, '${uid}', NULL, '${data}')");
+}
+
+function updatePlayerInfo($player_id, $values) {
+ global $db;
+ $db->put("INSERT INTO player (player_id, full_name, team, `number`, image, `position`) VALUES ('${player_id}', '${values['full_name']}', '${values['team']}', '${values['number']}', '${values['image']}', '${values['position']}') ON DUPLICATE KEY UPDATE full_name = '${values['full_name']}', team = '${values['team']}', `number` = '${values['number']}', image = '${values['image']}', `position` = '${values['position']}'");
+}
+
diff --git a/src/generateJSON.php b/src/generateJSON.php
new file mode 100644
index 0000000..b178b8e
--- /dev/null
+++ b/src/generateJSON.php
@@ -0,0 +1,13 @@
+generateReport();
+$json = [];
+foreach ($analysis as $player => $values) {
+ $json[$player]['stats'] = getPlayerStats($player);
+ $json[$player]['analysis'] = $values;
+ $json[$player]['info'] = getPlayerInfo($player)[0];
+}
+
+writeToFile(json_encode($json), __DIR__ . '/../../react/public/playerData.json');
diff --git a/src/helper.php b/src/helper.php
new file mode 100644
index 0000000..37e5f9f
--- /dev/null
+++ b/src/helper.php
@@ -0,0 +1,152 @@
+ str_replace("'", '', $player['name']['full']),
+ 'team' => $player['editorial_team_abbr'],
+ 'number' => $player['uniform_number'],
+ 'image' => $player['image_url'],
+ 'position' => $player['display_position'],
+ ];
+ }
+ return $player_info;
+}
+
+function formatOwnedPlayerInfo($response) {
+ $player_info = [];
+ foreach ($response['team']['roster']['players']['player'] as $player) {
+ $player_info[$player['player_id']] = [
+ 'full_name' => str_replace("'", '', $player['name']['full']),
+ 'team' => $player['editorial_team_abbr'],
+ 'number' => $player['uniform_number'],
+ 'image' => $player['image_url'],
+ 'position' => $player['display_position'],
+ ];
+ }
+ return $player_info;
+}
+
+function formatPlayerStats($response, $scored_stats) {
+ $stats = [];
+ foreach ($response['player']['player_stats']['stats']['stat'] as $stat_id => $stat) {
+ if (array_key_exists($stat['stat_id'], $scored_stats)) {
+ switch ($stat['stat_id']){
+ case 0:
+ $stats['gp'] = $stat['value'];
+ break;
+ case 12:
+ $stats['pts'] = $stat['value'];
+ break;
+ case 15:
+ $stats['reb'] = $stat['value'];
+ break;
+ case 16:
+ $stats['ast'] = $stat['value'];
+ break;
+ case 17:
+ $stats['blk'] = $stat['value'];
+ break;
+ case 18:
+ $stats['stl'] = $stat['value'];
+ break;
+ case 19:
+ $stats['trn'] = $stat['value'];
+ break;
+ }
+ }
+ }
+ return $stats;
+}
+
+function formatStats($scored_stats) {
+ $stats = [];
+ foreach ($scored_stats as $stat_id => $value) {
+ switch ($stat_id){
+ case 0:
+ $stats['gp'] = $value;
+ break;
+ case 12:
+ $stats['pts'] = $value;
+ break;
+ case 15:
+ $stats['reb'] = $value;
+ break;
+ case 16:
+ $stats['ast'] = $value;
+ break;
+ case 17:
+ $stats['blk'] = $value;
+ break;
+ case 18:
+ $stats['stl'] = $value;
+ break;
+ case 19:
+ $stats['trn'] = $value;
+ break;
+ }
+ }
+ return $stats;
+}
+
+
diff --git a/src/updateDatabase.php b/src/updateDatabase.php
new file mode 100644
index 0000000..594da58
--- /dev/null
+++ b/src/updateDatabase.php
@@ -0,0 +1,22 @@
+getFreeAgents();
+
+// Get all owned players
+$owned_players = $sc->getOwnedPlayers();
+
+// Get data for all free agents
+foreach ($freeagents as $player) {
+ $sc->getPlayerStats($player);
+}
+
+// Get data for all owned players
+foreach ($owned_players as $players) {
+ foreach ($players as $player) {
+ $sc->getPlayerStats($player);
+ }
+}
diff --git a/tmp/.gitkeep b/tmp/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/tmp/auth/.gitkeep b/tmp/auth/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/tmp/data/.gitkeep b/tmp/data/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/tmp/data/players/.gitkeep b/tmp/data/players/.gitkeep
deleted file mode 100644
index e69de29..0000000