ILIAS  trunk Revision v11.0_alpha-1713-gd8962da2f67
All Data Structures Namespaces Files Functions Variables Enumerations Enumerator Modules Pages
class.ilXapiStatementEvaluation.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
31 {
36  protected array $resultStatusByXapiVerbMap = [
37  ilCmiXapiVerbList::COMPLETED => "completed",
38  ilCmiXapiVerbList::PASSED => "passed",
39  ilCmiXapiVerbList::FAILED => "failed",
41  ];
42 
43  protected array $resultProgressByXapiVerbMap = [
44  ilCmiXapiVerbList::PROGRESSED => "progressed",
45  ilCmiXapiVerbList::EXPERIENCED => "experienced"
46  ];
47 
48  protected ilObject $object;
49 
50  //todo
51  protected ilLogger $log;
52 
53  protected ?int $lpMode;
54 
58  public function __construct(ilLogger $log, ilObject $object)
59  {
60  $this->log = $log;
61  $this->object = $object;
62 
63  $objLP = ilObjectLP::getInstance($this->object->getId());
64  $this->lpMode = $objLP->getCurrentMode();
65  }
66 
67  public function evaluateReport(ilCmiXapiStatementsReport $report): void
68  {
69  foreach ($report->getStatements() as $xapiStatement) {
70  #$this->log->debug(
71  # "handle statement:\n".json_encode($xapiStatement, JSON_PRETTY_PRINT)
72  #);
73 
74  // ensure json decoded non assoc
75  $xapiStatement = json_decode(json_encode($xapiStatement));
76  $cmixUser = $this->getCmixUser($xapiStatement);
77 
78  $this->evaluateStatement($xapiStatement, $cmixUser->getUsrId());
79 
80  $this->log->debug('update lp for object (' . $this->object->getId() . ')');
81  if ($cmixUser->getUsrId() != ANONYMOUS_USER_ID) {
82  ilLPStatusWrapper::_updateStatus($this->object->getId(), $cmixUser->getUsrId());
83  }
84  }
85  }
86 
87  public function getCmixUser(object $xapiStatement): \ilCmiXapiUser
88  {
89  $cmixUser = null;
90  if ($this->object->getContentType() == ilObjCmiXapi::CONT_TYPE_CMI5) {
92  $this->object->getId(),
93  $xapiStatement->actor->account->name
94  );
95  } else {
97  $this->object->getId(),
98  str_replace('mailto:', '', $xapiStatement->actor->mbox)
99  );
100  }
101  return $cmixUser;
102  }
103 
104  public function evaluateStatement(object $xapiStatement, int $usrId): void
105  {
106  global $DIC;
107  $xapiVerb = $this->getXapiVerb($xapiStatement);
108 
109  if ($this->isValidXapiStatement($xapiStatement)) {
110  // result status and if exists scaled score
111  if ($this->hasResultStatusRelevantXapiVerb($xapiVerb)) {
112  if (!$this->isValidObject($xapiStatement)) {
113  return;
114  }
115  $userResult = $this->getUserResult($usrId);
116 
117  $oldResultStatus = $userResult->getStatus();
118  $newResultStatus = $this->getResultStatusForXapiVerb($xapiVerb);
119 
120  // this is for both xapi and cmi5
121  if ($this->isResultStatusToBeReplaced($oldResultStatus, $newResultStatus)) {
122  $this->log->debug("isResultStatusToBeReplaced: true");
123  $userResult->setStatus($newResultStatus);
124  }
125 
126  if ($this->hasXapiScore($xapiStatement)) {
127  $xapiScore = $this->getXapiScore($xapiStatement);
128  $this->log->debug("Score: " . $xapiScore);
129  $userResult->setScore((float) $xapiScore);
130  }
131  $userResult->save();
132 
133  // only cmi5
134  if ($this->object->getContentType() == ilObjCmiXapi::CONT_TYPE_CMI5) {
135  if (($xapiVerb == ilCmiXapiVerbList::COMPLETED || $xapiVerb == ilCmiXapiVerbList::PASSED) && $this->isLpModeInterestedInResultStatus($newResultStatus, false)) {
136  // it is possible to check against authToken usrId!
137  $cmixUser = $this->getCmixUser($xapiStatement);
138  $cmixUser->setSatisfied(true);
139  $cmixUser->save();
140  $this->sendSatisfiedStatement($cmixUser);
141  }
142  }
143  }
144  // result progress (i think only cmi5 relevant)
145  if ($this->hasResultProgressRelevantXapiVerb($xapiVerb)) {
146  $userResult = $this->getUserResult($usrId);
147  $progressedScore = $this->getProgressedScore($xapiStatement);
148  if ($progressedScore !== null && $progressedScore > 0) {
149  $userResult->setScore((float) ($progressedScore / 100));
150  $userResult->save();
151  }
152  }
153  }
154  }
155 
156  protected function isValidXapiStatement(object $xapiStatement): bool
157  {
158  if (!isset($xapiStatement->actor)) {
159  return false;
160  }
161 
162  if (!isset($xapiStatement->verb) || !isset($xapiStatement->verb->id)) {
163  return false;
164  }
165 
166  if (!isset($xapiStatement->object) || !isset($xapiStatement->object->id)) {
167  return false;
168  }
169 
170  return true;
171  }
172 
176  protected function isValidObject(object $xapiStatement): bool
177  {
178  if ($xapiStatement->object->id != $this->object->getActivityId()) {
179  $this->log->debug($xapiStatement->object->id . " != " . $this->object->getActivityId());
180  return false;
181  }
182  return true;
183  }
184 
185 
186  protected function getXapiVerb(object $xapiStatement): string
187  {
188  return $xapiStatement->verb->id;
189  }
190 
191  protected function getResultStatusForXapiVerb(string $xapiVerb): string
192  {
193  return $this->resultStatusByXapiVerbMap[$xapiVerb];
194  }
195 
196  protected function hasResultStatusRelevantXapiVerb(string $xapiVerb): bool
197  {
198  return isset($this->resultStatusByXapiVerbMap[$xapiVerb]);
199  }
200 
201  protected function getResultProgressForXapiVerb(string $xapiVerb)
202  {
203  return $this->resultProgressByXapiVerbMap[$xapiVerb];
204  }
205 
206  protected function hasResultProgressRelevantXapiVerb(string $xapiVerb): bool
207  {
208  return isset($this->resultProgressByXapiVerbMap[$xapiVerb]);
209  }
210 
211  protected function hasXapiScore(object $xapiStatement): bool
212  {
213  if (!isset($xapiStatement->result)) {
214  return false;
215  }
216 
217  if (!isset($xapiStatement->result->score)) {
218  return false;
219  }
220 
221  if (!isset($xapiStatement->result->score->scaled)) {
222  return false;
223  }
224 
225  return true;
226  }
227 
228  protected function getXapiScore(object $xapiStatement)
229  {
230  return $xapiStatement->result->score->scaled;
231  }
232 
233  protected function getProgressedScore(object $xapiStatement): ?float
234  {
235  if (!isset($xapiStatement->result)) {
236  return null;
237  }
238 
239  if (!isset($xapiStatement->result->extensions)) {
240  return null;
241  }
242 
243  if (!isset($xapiStatement->result->extensions->{'https://w3id.org/xapi/cmi5/result/extensions/progress'})) {
244  return null;
245  }
246  return (float) $xapiStatement->result->extensions->{'https://w3id.org/xapi/cmi5/result/extensions/progress'};
247  }
248 
249  protected function getUserResult(int $usrId): \ilCmiXapiResult
250  {
251  try {
252  $result = ilCmiXapiResult::getInstanceByObjIdAndUsrId($this->object->getId(), $usrId);
253  } catch (ilCmiXapiException $e) {
255  $result->setObjId($this->object->getId());
256  $result->setUsrId($usrId);
257  }
258 
259  return $result;
260  }
261 
262  protected function isResultStatusToBeReplaced(string $oldResultStatus, string $newResultStatus): bool
263  {
264  if (!$this->isLpModeInterestedInResultStatus($newResultStatus)) {
265  $this->log->debug("isLpModeInterestedInResultStatus: false");
266  return false;
267  }
268 
269  if (!$this->doesNewResultStatusDominateOldOne($oldResultStatus, $newResultStatus)) {
270  $this->log->debug("doesNewResultStatusDominateOldOne: false");
271  return false;
272  }
273 
274  if ($this->needsAvoidFailedEvaluation($oldResultStatus, $newResultStatus)) {
275  $this->log->debug("needsAvoidFailedEvaluation: false");
276  return false;
277  }
278 
279  return true;
280  }
281 
282  protected function isLpModeInterestedInResultStatus(string $resultStatus, ?bool $deactivated = true): ?bool
283  {
284  if ($this->lpMode == ilLPObjSettings::LP_MODE_DEACTIVATED) {
285  return $deactivated;
286  }
287 
288  switch ($resultStatus) {
289  case 'failed':
290 
291  return in_array($this->lpMode, [
295  ]);
296 
297  case 'passed':
298 
299  return in_array($this->lpMode, [
304  ]);
305 
306  case 'completed':
307 
308  return in_array($this->lpMode, [
313  ]);
314  }
315 
316  return false;
317  }
318 
319  protected function doesNewResultStatusDominateOldOne(string $oldResultStatus, string $newResultStatus): bool
320  {
321  if ($oldResultStatus == '') {
322  return true;
323  }
324 
325  if (in_array($newResultStatus, ['passed', 'failed'])) {
326  return true;
327  }
328 
329  if (!in_array($oldResultStatus, ['passed', 'failed'])) {
330  return true;
331  }
332 
333  return false;
334  }
335 
336  protected function needsAvoidFailedEvaluation(string $oldResultStatus, string $newResultStatus): bool
337  {
338  if (!$this->object->isKeepLpStatusEnabled()) {
339  return false;
340  }
341 
342  if ($newResultStatus != 'failed') {
343  return false;
344  }
345 
346  return $oldResultStatus == 'completed' || $oldResultStatus == 'passed';
347  }
348 
349  protected function sendSatisfiedStatement(ilCmiXapiUser $cmixUser): void
350  {
351  global $DIC;
352 
353  $lrsType = $this->object->getLrsType();
354  $defaultLrs = $lrsType->getLrsEndpoint();
355  //$fallbackLrs = $lrsType->getLrsFallbackEndpoint();
356  $defaultBasicAuth = $lrsType->getBasicAuth();
357  //$fallbackBasicAuth = $lrsType->getFallbackBasicAuth();
358  $defaultHeaders = [
359  'X-Experience-API-Version' => '1.0.3',
360  'Authorization' => $defaultBasicAuth,
361  'Content-Type' => 'application/json;charset=utf-8',
362  'Cache-Control' => 'no-cache, no-store, must-revalidate'
363  ];
364  /*
365  $fallbackHeaders = [
366  'X-Experience-API-Version' => '1.0.3',
367  'Authorization' => $fallbackBasicAuth,
368  'Content-Type' => 'application/json;charset=utf-8',
369  'Cache-Control' => 'no-cache, no-store, must-revalidate'
370  ];
371  */
372  $satisfiedStatement = $this->object->getSatisfiedStatement($cmixUser);
373  $satisfiedStatementParams = [];
374  $satisfiedStatementParams['statementId'] = $satisfiedStatement['id'];
375  $defaultStatementsUrl = $defaultLrs . "/statements";
376  $defaultSatisfiedStatementUrl = $defaultStatementsUrl . '?' . ilCmiXapiAbstractRequest::buildQuery($satisfiedStatementParams);
377 
378  $client = new GuzzleHttp\Client();
379  $req_opts = array(
380  GuzzleHttp\RequestOptions::VERIFY => true,
381  GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 10,
382  GuzzleHttp\RequestOptions::HTTP_ERRORS => false
383  );
384 
385  $defaultSatisfiedStatementRequest = new GuzzleHttp\Psr7\Request(
386  'PUT',
387  $defaultSatisfiedStatementUrl,
388  $defaultHeaders,
389  json_encode($satisfiedStatement)
390  );
391  $promises = array();
392  $promises['defaultSatisfiedStatement'] = $client->sendAsync($defaultSatisfiedStatementRequest, $req_opts);
393  try {
394  $responses = GuzzleHttp\Promise\Utils::settle($promises)->wait();
395  $body = '';
396  ilCmiXapiAbstractRequest::checkResponse($responses['defaultSatisfiedStatement'], $body, [204]);
397  } catch (Exception $e) {
398  $this->log->error('error:' . $e->getMessage());
399  }
400  }
401 }
isResultStatusToBeReplaced(string $oldResultStatus, string $newResultStatus)
const ANONYMOUS_USER_ID
Definition: constants.php:27
isLpModeInterestedInResultStatus(string $resultStatus, ?bool $deactivated=true)
doesNewResultStatusDominateOldOne(string $oldResultStatus, string $newResultStatus)
evaluateStatement(object $xapiStatement, int $usrId)
sendSatisfiedStatement(ilCmiXapiUser $cmixUser)
__construct(ilLogger $log, ilObject $object)
ilXapiStatementEvaluation constructor.
static getInstanceByObjIdAndUsrId(int $objId, int $usrId)
array $resultStatusByXapiVerbMap
http://adlnet.gov/expapi/verbs/satisfied: should never be sent by AU https://github.com/AICC/CMI-5_Spec_Current/blob/quartz/cmi5_spec.md#939-satisfied
needsAvoidFailedEvaluation(string $oldResultStatus, string $newResultStatus)
while($session_entry=$r->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) return null
$client
static getInstanceByObjectIdAndUsrIdent(int $objId, string $usrIdent)
global $DIC
Definition: shib_login.php:22
evaluateReport(ilCmiXapiStatementsReport $report)
const LP_MODE_CMIX_COMPL_OR_PASSED_WITH_FAILED
static buildQuery(array $params, $encoding=PHP_QUERY_RFC3986)
static getInstance(int $obj_id)
static checkResponse(array $response, &$body, array $allowedStatus=[200, 204])
static _updateStatus(int $a_obj_id, int $a_usr_id, ?object $a_obj=null, bool $a_percentage=false, bool $a_force_raise=false)