ILIAS  release_9 Revision v9.13-25-g2c18ec4c24f
class.assOrderingQuestionImport.php
Go to the documentation of this file.
1 <?php
28 {
32  public $object;
33 
47  public function fromXML(&$item, $questionpool_id, &$tst_id, &$tst_object, &$question_counter, $import_mapping): array
48  {
49  global $DIC;
50  $ilUser = $DIC['ilUser'];
51 
52  // empty session variable for imported xhtml mobs
53  ilSession::clear('import_mob_xhtml');
54 
55  $presentation = $item->getPresentation();
56  $shuffle = 0;
57  $foundimage = false;
58  $answers = [];
59  $type = OQ_TERMS;
60 
61  foreach ($presentation->order as $entry) {
62  switch ($entry["type"]) {
63  case "response":
64  $response = $presentation->response[$entry["index"]];
65  $type = $response->getIdent();
66  if ($response->getIdent() == 'OQP') {
67  $type = OQ_PICTURES;
68  } elseif ($response->getIdent() == 'OQNP') {
69  $type = OQ_NESTED_PICTURES;
70  } elseif ($response->getIdent() == 'OQNT') {
71  $type = OQ_NESTED_TERMS;
72  } elseif ($response->getIdent() == 'OQT') {
73  $type = OQ_TERMS;
74  }
75 
76  $rendertype = $response->getRenderType();
77  switch (strtolower(get_class($rendertype))) {
78  case "ilqtirenderchoice":
79  $shuffle = $rendertype->getShuffle();
80  $answerorder = 0;
81  foreach ($rendertype->response_labels as $response_label) {
82  $ident = $response_label->getIdent();
83  $answertext = "";
84  $answerimage = [];
85  $answerdepth = 0;
86  foreach ($response_label->material as $mat) {
87  for ($m = 0; $m < $mat->getMaterialCount(); $m++) {
88  $foundmat = $mat->getMaterial($m);
89 
90  if (strcmp($foundmat["material"]->getLabel() ?? '', "answerdepth") == 0) {
91  $answerdepth = $foundmat["material"]->getContent();
92  }
93  if (strcmp($foundmat["type"], "mattext") == 0
94  && strcmp($foundmat["material"]->getLabel() ?? '', "answerdepth") != 0) {
95  $answertext .= $foundmat["material"]->getContent();
96  }
97  if (strcmp($foundmat["type"], "matimage") == 0
98  && strcmp($foundmat["material"]->getLabel(), "answerdepth") != 0) {
99  $foundimage = true;
100  $answerimage = [
101  "imagetype" => $foundmat["material"]->getImageType(),
102  "label" => $foundmat["material"]->getLabel(),
103  "content" => $foundmat["material"]->getContent()
104  ];
105  }
106  }
107  }
108  $answers[$answerorder] = [
109  'ident' => $ident,
110  "answertext" => $answertext,
111  "answerimage" => $answerimage,
112  "points" => 0,
113  "answerorder" => $answerorder,
114  "answerdepth" => $answerdepth,
115  "correctness" => "",
116  "action" => ""
117  ];
118  $answerorder++;
119  }
120  break;
121  }
122  break;
123  }
124  }
125 
126  $feedbacksgeneric = [];
127  foreach ($item->resprocessing as $resprocessing) {
128  foreach ($resprocessing->respcondition as $respcondition) {
129  $ident = '';
130  $correctness = 1;
131  $conditionvar = $respcondition->getConditionvar();
132  foreach ($conditionvar->order as $order) {
133  switch ($order["field"]) {
134  case "arr_not":
135  $correctness = 0;
136  break;
137  case "varequal":
138  $ident = $conditionvar->varequal[$order["index"]]->getContent();
139  $orderindex = $conditionvar->varequal[$order["index"]]->getIndex();
140  break;
141  }
142  }
143  foreach ($respcondition->setvar as $setvar) {
144  if ($ident !== '') {
145  $answers[$ident]['solutionorder'] = $orderindex;
146  $answers[$ident]['action'] = $setvar->getAction();
147  $answers[$ident]['points'] = $setvar->getContent();
148  }
149  }
150  if (!is_array($respcondition->displayfeedback)) {
151  continue;
152  }
153 
154  foreach ($respcondition->displayfeedback as $feedbackpointer) {
155  if ($feedbackpointer->getLinkrefid() === '') {
156  continue;
157  }
158 
159  foreach ($item->itemfeedback as $ifb) {
160  if ($ifb->getIdent() === 'response_allcorrect') {
161  // found a feedback for the identifier
162  foreach ($ifb->material as $material) {
163  $feedbacksgeneric[1] = $material;
164  }
165  foreach ($ifb->flow_mat as $fmat) {
166  foreach ($fmat->material as $material) {
167  $feedbacksgeneric[1] = $material;
168  }
169  }
170  continue;
171  }
172 
173  if ($ifb->getIdent() === 'response_onenotcorrect') {
174  // found a feedback for the identifier
175  foreach ($ifb->material as $material) {
176  $feedbacksgeneric[0] = $material;
177  }
178  foreach ($ifb->flow_mat as $fmat) {
179  foreach ($fmat->material as $material) {
180  $feedbacksgeneric[0] = $material;
181  }
182  }
183  }
184  }
185  }
186  }
187  }
188 
189  $itemfeedbacks = $this->getFeedbackAnswerSpecific($item, 'link_');
190 
191  $this->addGeneralMetadata($item);
192  $this->object->setTitle($item->getTitle());
193  $this->object->setNrOfTries((int) $item->getMaxattempts());
194  $this->object->setComment($item->getComment());
195  $this->object->setAuthor($item->getAuthor());
196  $this->object->setOwner($ilUser->getId());
197  $this->object->setQuestion($this->QTIMaterialToString($item->getQuestiontext()));
198  $this->object->setOrderingType($type);
199  $this->object->setObjId($questionpool_id);
200  $this->object->setThumbSize(
201  $this->deduceThumbSizeFromImportValue((int) $item->getMetadataEntry('thumb_geometry'))
202  );
203  $this->object->setElementHeight($item->getMetadataEntry('element_height')
204  ? (int) $item->getMetadataEntry('element_height')
205  : null);
206  $this->object->setShuffle($shuffle);
207  $this->object->setPoints(0);
208  $this->object->saveQuestionDataToDb();
209  $points = 0;
210  $solanswers = [];
211 
212  foreach ($answers as $answer) {
213  if (isset($answer["solutionorder"])) {
214  $solanswers[$answer["solutionorder"]] = $answer;
215  }
216  }
217  ksort($solanswers);
218  $position = 0;
219  $element_list = $this->object->getOrderingElementList();
220  foreach ($solanswers as $answer) {
221  $points += $answer["points"];
222 
223  $element = new ilAssOrderingElement();
224 
225  if ($element->isExportIdent($answer['ident'])) {
226  $element->setExportIdent($answer['ident']);
227  } else {
228  $element = $element->withPosition($position++);
229  if (isset($answer['answerdepth'])) {
230  $element = $element->withIndentation((int) $answer['answerdepth']);
231  }
232  }
233 
234  if ($this->object->isImageOrderingType()) {
235  $filename = $this->handleUploadedfile($answer);
236  if ($filename !== null) {
237  $element = $element->withContent($filename);
238  }
239  } else {
240  $element = $element->withContent($answer["answertext"]);
241  }
242 
243  $element_list->addElement($element);
244  }
245  $this->object->setOrderingElementList($element_list);
246  $points = ($item->getMetadataEntry("points") > 0) ? $item->getMetadataEntry('points') : $points;
247  $this->object->setPoints($points);
248  // additional content editing mode information
249  $this->object->setAdditionalContentEditingMode(
251  );
252  $this->object->saveToDb();
253  $this->importSuggestedSolutions($this->object->getId(), $item->suggested_solutions);
254  foreach ($feedbacksgeneric as $correctness => $material) {
255  $m = $this->QTIMaterialToString($material);
256  $feedbacksgeneric[$correctness] = $m;
257  }
258  $questiontext = $this->object->getQuestion();
259 
260  // handle the import of media objects in XHTML code
261  if (is_array(ilSession::get("import_mob_xhtml"))) {
262  foreach (ilSession::get("import_mob_xhtml") as $mob) {
263  if ($tst_id > 0) {
264  $importfile = $this->getTstImportArchivDirectory() . '/' . $mob["uri"];
265  } else {
266  $importfile = $this->getQplImportArchivDirectory() . '/' . $mob["uri"];
267  }
268 
269  global $DIC; /* @var ILIAS\DI\Container $DIC */
270  $DIC['ilLog']->write(__METHOD__ . ': import mob from dir: ' . $importfile);
271 
272  $media_object = ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, false);
273  ilObjMediaObject::_saveUsage($media_object->getId(), "qpl:html", $this->object->getId());
274  $questiontext = str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $questiontext);
275  foreach ($this->object->getOrderingElementList() as $element) {
276  $element->setContent(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $element->getContent()));
277  }
278  foreach ($feedbacksgeneric as $correctness => $material) {
279  $feedbacksgeneric[$correctness] = str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $material);
280  }
281  foreach ($itemfeedbacks as $ident => $material) {
282  $itemfeedbacks[$ident] = str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $material);
283  }
284  }
285  }
286  $this->object->setQuestion(ilRTE::_replaceMediaObjectImageSrc($questiontext, 1));
287  foreach ($this->object->getOrderingElementList() as $element) {
288  $element->setContent(ilRTE::_replaceMediaObjectImageSrc($element->getContent(), 1));
289  }
290  foreach ($feedbacksgeneric as $correctness => $material) {
291  $this->object->feedbackOBJ->importGenericFeedback(
292  $this->object->getId(),
293  $correctness,
295  );
296  }
297  foreach ($itemfeedbacks as $ident => $material) {
298  $index = $this->fetchIndexFromFeedbackIdent($ident, 'link_');
299 
300  $this->object->feedbackOBJ->importSpecificAnswerFeedback(
301  $this->object->getId(),
302  0,
303  $index,
305  );
306  }
307  $this->object->saveToDb();
308  if (isset($tst_id) && $tst_id !== $questionpool_id) {
309  $qplQid = $this->object->getId();
310  $tstQid = $this->object->duplicate(true, '', '', -1, $tst_id);
311  $tst_object->questions[$question_counter++] = $tstQid;
312  $import_mapping[$item->getIdent()] = ["pool" => $qplQid, "test" => $tstQid];
313  return $import_mapping;
314  }
315 
316  if ($tst_id > 0) {
317  $tst_object->questions[$question_counter++] = $this->object->getId();
318  $import_mapping[$item->getIdent()] = ["pool" => 0, "test" => $this->object->getId()];
319  return $import_mapping;
320  }
321 
322  $import_mapping[$item->getIdent()] = ["pool" => $this->object->getId(), "test" => 0];
323  return $import_mapping;
324  }
325 
326  protected function handleUploadedFile(array $answer): ?string
327  {
328  $image = base64_decode($answer["answerimage"]["content"] ?? '');
329  $image_file_name = $answer['answerimage']['label'] ?? '';
330  $tmp_path = ilFileUtils::ilTempnam();
331 
332  $file_handle = fopen($tmp_path, "wb");
333  if ($file_handle === false) {
334  return null;
335  }
336  fwrite($file_handle, $image);
337  fclose($file_handle);
338 
339  $filename_path_parts = explode(".", $image_file_name);
340  $suffix = strtolower(array_pop($filename_path_parts));
341  if (!in_array($suffix, assOrderingQuestion::VALID_UPLOAD_SUFFIXES)) {
342  return null;
343  }
344 
345  $this->ensureImagePathExists();
346  $target_filename = $this->object->buildHashedImageFilename($image_file_name, true);
347  $target_filepath = $this->object->getImagePath() . $target_filename;
348  if (rename($tmp_path, $target_filepath)) {
349  $thumb_path = $this->object->getImagePath() . $this->object->getThumbPrefix() . $target_filename;
350  ilShellUtil::convertImage($target_filepath, $thumb_path, "JPEG", $this->object->getThumbSize());
351  return $target_filename;
352  }
353 
354  return null;
355  }
356 
357  protected function ensureImagePathExists()
358  {
359  if (!file_exists($this->object->getImagePath())) {
360  ilFileUtils::makeDirParents($this->object->getImagePath());
361  }
362  }
363 }
static _replaceMediaObjectImageSrc(string $a_text, int $a_direction=0, string $nic='')
Replaces image source from mob image urls with the mob id or replaces mob id with the correct image s...
static get(string $a_var)
getFeedbackAnswerSpecific(ilQTIItem $item, $prefix='response_')
deduceThumbSizeFromImportValue(?int $size)
addGeneralMetadata(ilQTIItem $item)
fromXML(&$item, $questionpool_id, &$tst_id, &$tst_object, &$question_counter, $import_mapping)
Creates a question from a QTI file.
const IL_INST_ID
Definition: constants.php:40
QTIMaterialToString(ilQTIMaterial $a_material)
Reads an QTI material tag and creates a text or XHTML string.
const OQ_NESTED_TERMS
fetchAdditionalContentEditingModeInformation($qtiItem)
fetches the "additional content editing mode" information from qti item and falls back to ADDITIONAL_...
static _saveUsage(int $a_mob_id, string $a_type, int $a_id, int $a_usage_hist_nr=0, string $a_lang="-")
Save usage of mob within another container (e.g.
$response
Definition: xapitoken.php:93
getQplImportArchivDirectory()
returns the full path to extracted qpl import archiv (qpl import dir + qpl archiv subdir) ...
static makeDirParents(string $a_dir)
Create a new directory and all parent directories.
global $DIC
Definition: feed.php:28
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
const OQ_PICTURES
Ordering question constants.
static convertImage(string $a_from, string $a_to, string $a_target_format="", string $a_geometry="", string $a_background_color="")
$filename
Definition: buildRTE.php:78
importSuggestedSolutions(int $question_id, array $solution_from_import)
static _saveTempFileAsMediaObject(string $name, string $tmp_name, bool $upload=true)
Create new media object and update page in db and return new media object.
static ilTempnam(?string $a_temp_path=null)
Returns a unique and non existing Path for e temporary file or directory.
const OQ_TERMS
const OQ_NESTED_PICTURES
getTstImportArchivDirectory()
returns the full path to extracted tst import archiv (tst import dir + tst archiv subdir) ...
Class for question imports.
static clear(string $a_var)
fetchIndexFromFeedbackIdent($feedbackIdent, $prefix='response_')