diff --git a/lib/statslib.php b/lib/statslib.php index 9dfd7f05f74..a8970faa62e 100644 --- a/lib/statslib.php +++ b/lib/statslib.php @@ -987,18 +987,24 @@ function stats_get_base_daily($time=0) { function stats_get_base_weekly($time=0) { global $CFG; - $time = stats_get_base_daily($time); + $datetime = new DateTime(); + $datetime->setTimestamp(stats_get_base_daily($time)); $startday = $CFG->calendar_startwday; core_date::set_default_server_timezone(); $thisday = date('w', $time); + $days = 0; + if ($thisday > $startday) { - $time = $time - (($thisday - $startday) * 60*60*24); + $days = $thisday - $startday; } else if ($thisday < $startday) { - $time = $time - ((7 + $thisday - $startday) * 60*60*24); + $days = 7 + $thisday - $startday; } - return $time; + + $datetime->sub(new DateInterval("P{$days}D")); + + return $datetime->getTimestamp(); } /** diff --git a/lib/tests/statslib_test.php b/lib/tests/statslib_test.php index f8ced493736..7af80e024f8 100644 --- a/lib/tests/statslib_test.php +++ b/lib/tests/statslib_test.php @@ -219,6 +219,34 @@ class core_statslib_testcase extends advanced_testcase { return $logfiles; } + /** + * Set of data for test_statlibs_get_base_weekly + * + * @return array Dates and timezones for which the first day of the week will be calculated + */ + public function get_base_weekly_provider() { + return [ + [ + "startwday" => 0, + "timezone" => 'America/Chicago', + "timestart" => '18-03-2017 22:00', + "expected" => '12-03-2017 00:00:00' + ], + [ + "startwday" => 0, + "timezone" => 'America/Chicago', + "date" => '25-03-2017 22:00', + "expected" => '19-03-2017 00:00:00' + ], + [ + "startwday" => 1, + "timezone" => 'Atlantic/Canary', + "date" => '06-08-2018 22:00', + "expected" => '06-08-2018 00:00:00' + ], + ]; + } + /** * Compare the expected stats to those in the database. * @@ -420,6 +448,27 @@ class core_statslib_testcase extends advanced_testcase { $this->assertEquals(24, ((1446526800 - 1446440400) / 60 ) / 60); } + /** + * Test the function that calculates the start of the week. + * + * @dataProvider get_base_weekly_provider + * @param int $startwday Day in which the week starts (Sunday = 0) + * @param string $timezone Default timezone + * @param string $timestart Date and time for which the first day of the week will be obtained + * @param string $expected Expected date of the first day of the week + */ + public function test_statslib_get_base_weekly($startwday, $timezone, $timestart, $expected) { + $this->setTimezone($timezone); + $time = strtotime($timestart); + $expected = strtotime($expected); + set_config('calendar_startwday', $startwday); + set_config('statslastweekly', $time); + + $weekstarttime = stats_get_base_weekly($time); + + $this->assertEquals($expected, $weekstarttime); + } + /** * Test the function that gets the action names. *