From c8628576e3ea4cf46c55bd4e5503a4d8d2548c31 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Tue, 21 Feb 2023 16:46:05 +0100 Subject: [PATCH] MDL-77254 h5p: Add support to restored states The restored states should be treated differently, to avoid resetting them by default the first time users access them. In that case, the first time users access to content with restored xAPI states, they should be displayed (instead of resetting them). --- h5p/classes/framework.php | 4 +++- h5p/classes/player.php | 24 ++++++++++++++++++++++++ lib/xapi/classes/local/state.php | 2 +- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/h5p/classes/framework.php b/h5p/classes/framework.php index b87a54bd0dc..33cba574f32 100644 --- a/h5p/classes/framework.php +++ b/h5p/classes/framework.php @@ -960,7 +960,9 @@ class framework implements H5PFrameworkInterface { // Reset user data. try { $xapihandler = handler::create($file->get_component()); - $xapihandler->reset_states($file->get_contextid()); + // Reset only entries with 'state' as stateid (the ones restored shouldn't be restored, because the H5P + // content hasn't been created yet). + $xapihandler->reset_states($file->get_contextid(), null, 'state'); } catch (xapi_exception $exception) { // This component doesn't support xAPI State, so no content needs to be reset. return; diff --git a/h5p/classes/player.php b/h5p/classes/player.php index 3492ffe1340..e8b12b45e18 100644 --- a/h5p/classes/player.php +++ b/h5p/classes/player.php @@ -277,6 +277,30 @@ class player { ); try { $state = $xapihandler->load_state($state); + if (!$state) { + // Check if the state has been restored from a backup for the current user. + $state = new state( + item_agent::create_from_user($USER), + $xapiobject, + 'restored', + null, + null + ); + $state = $xapihandler->load_state($state); + if ($state && !is_null($state->get_state_data())) { + // A restored state has been found. It will be replaced with one with the proper stateid and statedata. + $xapihandler->delete_state($state); + $state = new state( + item_agent::create_from_user($USER), + $xapiobject, + 'state', + $state->jsonSerialize(), + null + ); + $xapihandler->save_state($state); + } + } + if (!$state) { return $emptystatedata; } diff --git a/lib/xapi/classes/local/state.php b/lib/xapi/classes/local/state.php index 1850e13a142..ace985b02b7 100644 --- a/lib/xapi/classes/local/state.php +++ b/lib/xapi/classes/local/state.php @@ -72,7 +72,7 @@ class state implements JsonSerializable { /** * Return the data to serialize in case JSON state when needed. * - * @return stdClass The state data structure + * @return stdClass The state data structure. If statedata is null, this method will return an empty class. */ public function jsonSerialize(): stdClass { if ($this->statedata) {