ILIAS  release_10 Revision v10.1-43-ga1241a92c2f
class.ilLTIConsumerGradeServiceScores.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
31 {
33  {
34  parent::__construct($service);
35  $this->id = 'Score.collection';
36  $this->template = '/{context_id}/lineitems/{item_id}/lineitem/scores';
37  $this->variables[] = 'Scores.url';
38  $this->formats[] = 'application/vnd.ims.lis.v1.scorecontainer+json';
39  $this->formats[] = 'application/vnd.ims.lis.v1.score+json';
40  $this->methods[] = 'POST';
41  }
42 
47  {
48  $params = $this->parseTemplate();
49  $contextId = $params['context_id'];
50  $itemId = $params['item_id'];
51 
52  ilObjLTIConsumer::getLogger()->info("contextId: " . $contextId);
53  ilObjLTIConsumer::getLogger()->info("objId: " . $itemId);
54  ilObjLTIConsumer::getLogger()->info("request data: " . $response->getRequestData());
55 
56  // GET is disabled by the moment, but we have the code ready
57  // for a future implementation.
58 
59  //$container = empty($contentType) || ($contentType === $this->formats[0]);
60 
61  $typeid = 0;
62 
64  try {
65  $token = $this->checkTool(array($scope));
66  if (is_null($token)) {
67  throw new Exception('invalid request', 401);
68  }
69 
70  // Bug in Moodle as tool provider, should accept only "204 No Content" but schedules grade sync task will notices a failed status if not exactly 200
71  // see: http://www.imsglobal.org/spec/lti-ags/v2p0#score-service-scope-and-allowed-http-methods
72  //$response->setCode(204); // correct
73  $returnCode = 200;
74  $returnCode = $this->checkScore($response->getRequestData(), (int) $itemId);
75  $response->setCode($returnCode); // not really correct
76  } catch (Exception $e) {
77  $response->setCode($e->getCode());
78  $response->setReason($e->getMessage());
79  }
80  }
81 
82  protected function checkScore(string $requestData, int $objId): int
83  {
84  global $DIC; /* @var \ILIAS\DI\Container $DIC */
85 
86  $logger = $DIC->logger()->root();
87 
88  $logger->info('checkScore');
89  $score = json_decode($requestData);
90  //prüfe Userid
91  $userId = ilCmiXapiUser::getUsrIdForObjectAndUsrIdent($objId, $score->userId);
92  if ($userId == null) {
93  ilObjLTIConsumer::getLogger()->info('User not available');
94  throw new Exception('User not available', 404);
95  return 404;
96  }
97 
98  if (empty($score) ||
99  !isset($score->userId) ||
100  !isset($score->gradingProgress) ||
101  !isset($score->activityProgress) ||
102  !isset($score->timestamp) ||
103  isset($score->timestamp) && !self::validate_iso8601_date($score->timestamp) ||
104  (isset($score->scoreGiven) && !is_numeric($score->scoreGiven)) ||
105  (isset($score->scoreGiven) && !isset($score->scoreMaximum)) ||
106  (isset($score->scoreMaximum) && !is_numeric($score->scoreMaximum))
107  ) {
108  ilObjLTIConsumer::getLogger()->info('Incorrect score received');
109  ilObjLTIConsumer::getLogger()->dump($score);
110  throw new Exception('Incorrect score received', 400);
111  return 400;
112  }
113  //Achtung Ggfs. Timestamp prüfen falls schon was ankam
114  if (!isset($score->scoreMaximum)) {
115  $score->scoreMaximum = 1;
116  }
117  if (isset($score->scoreGiven)) {
118  if ($score->gradingProgress != 'FullyGraded') {
119  $score->scoreGiven = null;
120  }
121  }
122  $result = (float) $score->scoreGiven / (float) $score->scoreMaximum;
123  ilObjLTIConsumer::getLogger()->info("result: " . $result);
124 
125  $ltiObjRes = new ilLTIConsumerResultService();
126 
127  $ltiObjRes->readProperties($objId);
128  // check the object status
129  if (!$ltiObjRes->isAvailable()) {
130  throw new Exception('Tool for Object not available', 404);
131  return 404;
132  }
133 
134  if ($result >= $ltiObjRes->getMasteryScore()) {
136  } else {
138  }
139  $lp_percentage = (int) round(100 * $result);
140 
141  $consRes = ilLTIConsumerResult::getByKeys($objId, $userId, false);
142  if (empty($consRes)) {
143  ilObjLTIConsumer::getLogger()->info("lti_consumer_results_id not found!");
144  // throw new Exception('lti_consumer_results_id not found!', 404);
145  // return 404;
146  }
147  if (!isset($consRes->id)) {
148  $consRes->id = $DIC->database()->nextId('lti_consumer_results');
149  }
150  $DIC->database()->replace(
151  'lti_consumer_results',
152  array(
153  'id' => array('integer', $consRes->id)
154  ),
155  array(
156  'obj_id' => array('integer', $objId),
157  'usr_id' => array('integer', $userId),
158  'result' => array('float', $result)
159  )
160  );
161 
162  ilLPStatus::writeStatus($objId, $userId, $lp_status, $lp_percentage, true);
163 
164  $ltiTimestamp = DateTimeImmutable::createFromFormat(DateTimeInterface::RFC3339_EXTENDED, $score->timestamp);
165  if (!$ltiTimestamp) { //moodle 4
166  $ltiTimestamp = DateTimeImmutable::createFromFormat(DateTimeInterface::ISO8601, $score->timestamp);
167  }
168  if (!$ltiTimestamp) { //for example nothing
169  $ltiTimestamp = new DateTime('now');
170  }
171  $gradeValues = [
172  'id' => array('integer', $DIC->database()->nextId('lti_consumer_grades')),
173  'obj_id' => array('integer', $objId),
174  'usr_id' => array('integer', $userId),
175  'score_given' => array('float', $score->scoreGiven),
176  'score_maximum' => array('float', $score->scoreMaximum),
177  'activity_progress' => array('text', $score->activityProgress),
178  'grading_progress' => array('text', $score->gradingProgress),
179  'lti_timestamp' => array('timestamp',$ltiTimestamp->format("Y-m-d H:i:s")),
180  'stored' => array('timestamp', date("Y-m-d H:i:s"))
181  ];
182  $DIC->database()->insert('lti_consumer_grades', $gradeValues);
183 
184 
185 
186  return 200;
187  }
188 
189  public static function validate_iso8601_date(string $date): bool
190  {
191  if (preg_match('/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])' .
192  '(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))' .
193  '([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)' .
194  '?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/', $date) > 0) {
195  return true;
196  }
197  return false;
198  }
199 }
const LP_STATUS_COMPLETED_NUM
array $params
Template variables parsed from the resource template.
execute(ilLTIConsumerServiceResponse $response)
Execute the request for this resource.
$scope
Definition: ltiregstart.php:51
parseTemplate()
Parse the template for variables.
ilLTIConsumerServiceBase $service
Service associated with this resource.
const LP_STATUS_IN_PROGRESS_NUM
$response
Definition: xapitoken.php:90
$objId
Definition: xapitoken.php:55
static getUsrIdForObjectAndUsrIdent(int $objId, string $userIdent)
__construct(ilLTIConsumerServiceBase $service)
const SCOPE_GRADESERVICE_SCORE
Scope for access to Score service.
checkTool(array $scopes=array())
Check to make sure the request is valid.
$token
Definition: xapitoken.php:67
global $DIC
Definition: shib_login.php:25
setCode(int $code)
Set the response code.
static getByKeys(int $a_obj_id, int $a_usr_id, ?bool $a_create=false)
Get a result by object and user key.
setReason(string $reason)
Set the response reason.
__construct(Container $dic, ilPlugin $plugin)
static writeStatus(int $a_obj_id, int $a_user_id, int $a_status, int $a_percentage=0, bool $a_force_per=false, ?int &$a_old_status=self::LP_STATUS_NOT_ATTEMPTED_NUM)
Write status for user and object.