Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Statistics among Sports #11

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion classes/Charts.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ public static function altitudeChart ($user_id, $activity_id, $conn) {
//$cfg['title'] = 'Altura';
$cfg['width'] = 800;
$cfg['height'] = 300;
$cfg['average-line-visible'] = false;
$cfg['average-line-visible'] = true;
$cfg['horizontal-divider-visible'] = true;
$cfg['column-divider-visible'] = false;
$cfg['round-value-range'] = true;
Expand All @@ -376,6 +376,55 @@ public static function altitudeChart ($user_id, $activity_id, $conn) {
//Create phpMyGraph instance
$graph = new \phpMyGraph();
$graph->parseVerticalPolygonGraph($graph_data, $cfg, $altitude_offset);
#$graph->parseVerticalLineGraph($graph_data, $cfg, $altitude_offset);

}

public static function paceChart ($user_id, $activity_id, $conn) {
global $base_path;

$current_act = new Activity(array('id' => $activity_id, 'user_id' => $user_id));
$current_act->getActivity($conn);
$distancia = $current_act->distance/1000;

$pace = array();

$cumulated_pace = array();
foreach ($current_act->laps as $key => $value) {
$pace[] = round($value['pace'] * 60, 2);
$cumulated_pace[] = round((array_sum($pace)) / count($pace), 2);
}

//Set config directives
//$cfg['title'] = 'Altura';
$cfg['width'] = 800;
$cfg['height'] = 300;
$cfg['average-line-visible'] = false;
$cfg['horizontal-divider-visible'] = true;
$cfg['column-divider-visible'] = false;
$cfg['round-value-range'] = true;
$cfg['zero-line-visible'] = false;
$cfg['file-name'] = $base_path . "/users/" . $user_id . "/reports/alt_profile_" . $activity_id . ".png";
$cfg['label'] = "Pace vs Cumulated Pace";

//Create phpMyGraph instance
#$graph = new \phpMyGraph();
#$graph->parseVerticalLineGraph($pace, $cfg);
#$graph->parseVerticalLineGraph($pace, $cumulated_pace, $cfg);

# $graph = new verticalLineGraph();

//Parse
$graph = \phpMyGraph::factory('verticalLineGraph', $pace, $cfg);
$graph->parseCompare($pace, $cumulated_pace, $cfg);


# $graph = new verticalLineGraph();
//Parse
# $graph->parseCompare($data1, $data2, $cfg);

# $graph->parseCompare($pace, $cumulated_pace, $cfg);

}
}
?>
81 changes: 73 additions & 8 deletions classes/Goal.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,27 +166,60 @@ function unlinkRecord ($record_id, $conn) {
}
}

function retrieveInfo ($field, $conn) {
$sql_query = "SELECT SUM(" . $field . ") FROM records WHERE id IN (SELECT record_id FROM goal_records WHERE goal_id = :goal_id)";
function retrieveInfo ($sport_id, $field, $conn) {
$sql_query = "SELECT SUM(" . $field . ") FROM records WHERE sport_id = :sport_id AND id IN (SELECT record_id FROM goal_records WHERE goal_id = :goal_id) ";
$stmt = $conn->prepare($sql_query);
$stmt->bindParam(':sport_id', $sport_id);
$stmt->bindParam(':goal_id', $this->id);
$result = $stmt->execute();
if ($result) {
$row = $stmt->fetch(PDO::FETCH_NUM);
if ($row[0] == null or $row[0]==0) {
return 0;
} else {
return sprintf("%01.2f", $row[0]/1000000); # Result is in mm -> divide by 1000000
if ($field == "distance") {
#return sprintf("%01.2f", $row[0]/1000000); # Result is in mm -> divide by 1000000 A
return $row[0];
} else if ($field == "duration") {
#return Utils::formatMs($row[0]);
return $row[0];
}
}
} else {
throw new Exception("Error when retrieving " . $field . " data goal " . $this->id . ": " . json_encode($stmt->errorInfo()) . " | User: " . $this->user_id);
}
}

public function getKmDays($conn) {

/**
* Gets sports for current Goal.
*
* @param resource $conn Database resource
* @returns Array of sport_id availables
*/
function getSports($conn) {
$sql_query = "SELECT * FROM sports WHERE id IN (SELECT sport_id FROM records WHERE id IN (SELECT record_id FROM goal_records WHERE goal_id = :goal_id)) ORDER BY id ASC";
$stmt = $conn->prepare($sql_query);
$stmt->bindParam(':goal_id', $this->id);
$result = $stmt->execute();
$goal_sports = array();
if ($result) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$sport_tmp = new Sport($row);
$goal_sports[] = $sport_tmp;
}
} else {
throw new Exception("Error when retrieving sports (num: " . $stmt->rowCount() . ") for goal " . $this->id . ". Error: " . json_encode($stmt->errorInfo()) . " | User " . $this->id);
}
return $goal_sports;
}


public function getKmDurationDays($sport_id, $conn) {
# If only date is provided, mysql assumes time is 00h00:00
$sql_query = "SELECT start_time, distance FROM records WHERE id IN (SELECT record_id FROM goal_records WHERE goal_id = :goal_id) ORDER BY start_time ASC";
$sql_query = "SELECT sport_id, start_time, distance, duration FROM records WHERE sport_id = :sport_id AND id IN (SELECT record_id FROM goal_records WHERE goal_id = :goal_id) ORDER BY start_time ASC";
$stmt = $conn->prepare($sql_query);
$stmt->bindParam(':sport_id', $sport_id);
$stmt->bindParam(':goal_id', $this->id);
$result = $stmt->execute();
if ($result) {
Expand All @@ -195,12 +228,18 @@ public function getKmDays($conn) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
# Result is in mm -> divide by 1000000
$row['distance'] = sprintf("%01.2f", $row['distance']/1000000);
#$row['duration'] = Utils::formatMs($row['duration']);
$row['duration'] = sprintf("%01.2f", $row['duration'] / 3600000);
$dateAndTime = Utils::getDateAndTimeFromDateTime($row['start_time']);
$row['date'] = $dateAndTime['date'];
if(array_key_exists($row['date'], $date_values)) { //merge different activities from same day
$index = $date_values[$row['date']];
$old_value = $kms_goal[$index]['distance'];
$kms_goal[$index]['distance'] += $row['distance'];

$old_value = $kms_goal[$index]['duration'];
$kms_goal[$index]['distance'] += $row['duration'];

} else {
$kms_goal[] = $row;
$date_values[$row['date']] = count($kms_goal)-1;
Expand All @@ -213,10 +252,36 @@ public function getKmDays($conn) {
}

public function imgGoalReport ($img_path, $ttf, $conn) {
$kms = $this->retrieveInfo('distance', $conn);
$kms_duration = "";
// initial height
$banner_heigh = 30;
$goal_sports = $this->getSports($conn);
foreach ($goal_sports as $sport) {
// legent for this Sport, "Kms" and "Hours"
$met_type_label = Sport::$met_type_label[$sport->met];
if ($sport->met == Sport::Duration) {
$dato = $this->retrieveInfo($sport->id, 'duration', $conn);
if ($dato <> 0) {
$dato_formateado = Utils::formatMs($dato);
// rpad the name and lpad the value
$kms_duration = $kms_duration . str_pad($sport->abrev . ":" , 10, " ", STR_PAD_RIGHT) . str_pad($dato_formateado, 12, " ", STR_PAD_LEFT) . " " . $met_type_label . "\r\n";
// increase the banner_height
$banner_heigh = $banner_heigh + 18;
}
} else {
$dato = $this->retrieveInfo($sport->id, 'distance', $conn);
if ($dato <> 0) {
$dato_formateado = sprintf("%01.2f", $dato/1000000);
// rpad the name and lpad the value
$kms_duration = $kms_duration . str_pad ($sport->abrev . ":", 10, " ", STR_PAD_RIGHT) . str_pad($dato_formateado, 12, " ", STR_PAD_LEFT) . " " .$met_type_label . "\r\n";
// increase the banner_height
$banner_heigh = $banner_heigh + 18;
}
}
}
$num_days = Utils::daysToDate(date("Y-m-d"), date($this->goal_date));
$summary = "#" . $this->name . ": " . $kms . " km (quedan " . $num_days . " días)";
$im = @imagecreate(400, 30);
$summary = "#" . $this->name ." " . $this->goal_date . " (quedan " . $num_days . " días): \r\n" . $kms_duration;
$im = @imagecreate(400, $banner_heigh);
if ($im) {
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
Expand Down
118 changes: 113 additions & 5 deletions classes/Sport.php
Original file line number Diff line number Diff line change
@@ -1,15 +1,76 @@
<?php
namespace Entrenos;
use \PDO;
use \Exception;
use Entrenos\Utils\Utils;

/**
*
*/
class Sport {

public $id;
public $user_id;
public $name;
public $abrev;
public $extra_weight;
public $met;

// Defining met for Sport
const Distance = 0;
const Duration = 1;
public static $met_type_label = array(self::Distance => "Kms", self::Duration => "Horas");


// Defining sport id
const Running = 0;
const Cycling = 1;
const Walking = 2;
const Swimming = 3;
const Running = 1;
const Cycling = 2;
const Walking = 3;
const Swimming = 4;

public function __set($key,$value) {
$this->$key = $value;

}

public function __get($key) {
return $this->$key;
}

function __construct($data) {
foreach ($data as $key => $value) {
$this->__set($key,$value);
}
}


// ToDo: better localization, move this out of here!
public static $display_es = array(0 => "Correr", 1 => "Ciclismo", 2 => "Caminar", 3 => "Natación");
//public static $display_es = array(0 => "Correr", 1 => "Ciclismo", 2 => "Caminar", 3 => "Natación", 4=> "Eliptica");
//public static $met_type = array(0 => self::Distance, 1 => self::Distance, 2 => self::Distance, 3 => self::Distance, 4=> self::Duration);



/**
*
*
*/

public function insert ($conn) {
$sql_query = "INSERT INTO sports (user_id, name, abrev, extra_weight, met) VALUES (:user_id, :name, :abrev, :extra_weight, :met)";
$stmt = $conn->prepare($sql_query);
$stmt->bindParam(':user_id', $this->user_id);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':abrev', $this->abrev);
$stmt->bindParam(':extra_weight', $this->extra_weight);
$stmt->bindParam(':met', $this->met);
$result = $stmt->execute();
if ($result) {
$this->id = $conn->lastInsertId();
} else {
throw new Exception("Error when inserting sport data: " . json_encode($stmt->errorInfo()) . " | Query: " . $sql_query . " | Sport: " . json_encode($this));
}
}


/**
* Check which sport corresponds to provided pace
Expand All @@ -26,5 +87,52 @@ static public function check($pace, $distance = 0) {
}
return $result;
}

/**
* Retrieves all sports info found in database related to specified user
*
* @param string user_id
* object conn
* @return array
*/
public static function getUserSports ($user_id, $conn) {
$sql_query = "SELECT * FROM sports WHERE user_id = :user_id";
$stmt = $conn->prepare($sql_query);
$stmt->bindParam(':user_id', $user_id);
$result = $stmt->execute();
if ($result) {
$sports = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // TODO: retrieve objects instead of mapped arrays!
$sports[]=$row;
}
return $sports;
} else {
throw new Exception("Error when retrieving user's sports data: " . json_encode($stmt->errorInfo()) . " | User " . $user_id);
}
}

/**
* Retrieves all equipment data given unit's id
*
* @param object conn
* @return current object
*/
public function getSportData ($conn) {
$sql_query = "SELECT * FROM sports WHERE id = :sport_id";
$stmt = $conn->prepare($sql_query);
$stmt->bindParam(':sport_id', $this->id);
$result = $stmt->execute();
if ($result) {
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
foreach ($row as $key => $value) {
$this->__set($key,$value);
}
}
return $this; // ?
} else {
throw new Exception("Error when executing db query: " . json_encode($stmt->errorInfo()) . " | Sport " . $this->id);
}
}

}
?>
Loading