From 60eaa9bcb096b65bab115106c1f2f19c867225e4 Mon Sep 17 00:00:00 2001 From: Peter Date: Wed, 22 May 2019 18:51:49 +0800 Subject: [PATCH] MDL-55997 core_reports: modify user stats query to fix duplicate rows --- lib/statslib.php | 4 +++- report/stats/user.php | 31 +++++++++++++++++++++++++------ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/lib/statslib.php b/lib/statslib.php index a8970faa62e9..f449f07f5607 100644 --- a/lib/statslib.php +++ b/lib/statslib.php @@ -1196,11 +1196,13 @@ function stats_get_parameters($time,$report,$courseid,$mode,$roleid=0) { break; case STATS_REPORT_USER_VIEW: - $param->fields = 'statsreads as line1, statswrites as line2, statsreads+statswrites as line3'; + $param->fields = 'timeend, SUM(statsreads) AS line1, SUM(statswrites) AS line2, SUM(statsreads+statswrites) AS line3'; + $param->fieldscomplete = true; $param->line1 = get_string('statsuserreads'); $param->line2 = get_string('statsuserwrites'); $param->line3 = get_string('statsuseractivity'); $param->stattype = 'activity'; + $param->extras = "GROUP BY timeend"; break; // ******************** STATS_MODE_RANKED ******************** // diff --git a/report/stats/user.php b/report/stats/user.php index 547714234f02..ae71c4f8c202 100644 --- a/report/stats/user.php +++ b/report/stats/user.php @@ -124,14 +124,33 @@ $param = stats_get_parameters($time,STATS_REPORT_USER_VIEW,$course->id,STATS_MODE_DETAILED); $params = $param->params; - $param->table = 'user_'.$param->table; -$sql = 'SELECT id, timeend,'.$param->fields.' FROM {stats_'.$param->table.'} WHERE ' -.(($course->id == SITEID) ? '' : ' courseid = '.$course->id.' AND ') - .' userid = '.$user->id.' AND timeend >= '.$param->timeafter .$param->extras - .' ORDER BY timeend DESC'; -$stats = $DB->get_records_sql($sql, $params); //TODO: improve these params!! +// Build the conditions and parameters. +$wheres = [ + "userid = :userid", + "timeend >= :timeend", +]; +$params['userid'] = $user->id; +$params['timeend'] = $param->timeafter; +// Add condition for course ID when specified. +if ($course->id != SITEID) { + $wheres[] = "courseid = :courseid"; + $params['courseid'] = $course->id; +} +// Combine the conditions. +$wheresql = implode(" AND ", $wheres); + +// Build the query. +$sql = " + SELECT {$param->fields} + FROM {stats_{$param->table}} + WHERE {$wheresql} + {$param->extras} + ORDER BY timeend DESC"; + +// Fetch the stats data. +$stats = $DB->get_records_sql($sql, $params); if (empty($stats)) { print_error('nostatstodisplay', '', $CFG->wwwroot.'/course/user.php?id='.$course->id.'&user='.$user->id.'&mode=outline');