if ($key == 0) { $text .= '</tr>'; } else { $text .= '</tr>'; } } $text .= '</table>'; $pdf = Pdf::createPdf($text, 'L'); $file = http_post_data($filesystemURI . '/pdf', Pdf::encodePdf($pdf), true); $file = File::decodeFile($file); $file->setDisplayName('conditions.pdf'); $file = File::encodeFile($file); } elseif (isset($_GET['downloadConditionCsv'])) { $csv = Csv::createCsv($rows); $file = http_post_data($filesystemURI . '/csv', Csv::encodeCsv($csv), true); $file = File::decodeFile($file); $file->setDisplayName('conditions.csv'); $file = File::encodeFile($file); } echo $file; exit(0); } if (isset($_GET['sortby'])) { $condition_data['sortby'] = $_GET['sortby']; } if (isset($_GET['sortId'])) { $condition_data['sortId'] = $_GET['sortId']; } // construct a new header $h = Template::WithTemplateFile('include/Header/Header.template.html'); $h->bind($user_course_data);
/** * Processes a process * * Called when this component receives an HTTP POST request to * /process(/). */ public function postProcess() { $this->app->response->setStatus(201); $header = $this->app->request->headers->all(); $body = $this->app->request->getBody(); $process = Process::decodeProcess($body); // always been an array $arr = true; if (!is_array($process)) { $process = array($process); $arr = false; } // this array contains the indices of the inserted objects $res = array(); foreach ($process as $pro) { $eid = $pro->getExercise()->getId(); // loads the form from database $result = Request::routeRequest('GET', '/form/exercise/' . $eid, $this->app->request->headers->all(), '', $this->_formDb, 'form'); // checks the correctness of the query if ($result['status'] >= 200 && $result['status'] <= 299) { // only one form as result $forms = Form::decodeForm($result['content']); $forms = $forms[0]; $formdata = $pro->getRawSubmission()->getFile(); $timestamp = $formdata->getTimeStamp(); if ($timestamp === null) { $timestamp = time(); } if ($formdata !== null && $forms !== null) { $formdata = Form::decodeForm($formdata->getBody(true)); if (is_array($formdata)) { $formdata = $formdata[0]; } if ($formdata !== null) { // evaluate the formdata $points = 0; $answers = $formdata->getChoices(); $correctAnswers = $forms->getChoices(); $allcorrect = true; if ($forms->getType() == 0) { $parameter = explode(' ', strtolower($pro->getParameter())); if ($parameter === null || count($parameter) === 0 || $parameter[0] === '') { if (DefaultNormalizer::normalizeText($correctAnswers[0]->getText()) != DefaultNormalizer::normalizeText($answers[0]->getText())) { $allcorrect = false; } } elseif (strtolower($parameter[0]) === 'distance1') { $similarity = 0; similar_text(DefaultNormalizer::normalizeText($answers[0]->getText()), DefaultNormalizer::normalizeText($correctAnswers[0]->getText()), $similarity); if (isset($parameter[1])) { if ($similarity < $parameter[1]) { $allcorrect = false; } } else { if ($similarity < 100) { $allcorrect = false; } } } elseif (strtolower($parameter[0]) === 'regularexpression') { $i = 1; $test = $parameter[$i]; while ($i < count($parameter)) { if (@preg_match($test, DefaultNormalizer::normalizeText($answers[0]->getText())) !== false) { break; } $test .= ' ' . $parameter[$i]; $i++; } $match = @preg_match($test, DefaultNormalizer::normalizeText(DefaultNormalizer::normalizeText($answers[0]->getText()))); if ($match === false || $match == false || $test == '') { $allcorrect = false; } } } elseif ($forms->getType() == 1) { foreach ($correctAnswers as $mask) { $foundInStudentsAnswer = false; foreach ($answers as $answer) { if ($answer->getText() === $mask->getChoiceId()) { $foundInStudentsAnswer = true; break; } } if ($mask->getCorrect() === '1' && !$foundInStudentsAnswer) { $allcorrect = false; break; } elseif ($mask->getCorrect() === '0' && $foundInStudentsAnswer) { $allcorrect = false; break; } } } elseif ($forms->getType() == 2) { foreach ($correctAnswers as $mask) { $foundInStudentsAnswer = false; foreach ($answers as $answer) { if ($answer->getText() === $mask->getChoiceId()) { $foundInStudentsAnswer = true; break; } } if ($mask->getCorrect() === '1' && !$foundInStudentsAnswer) { $allcorrect = false; break; } elseif ($mask->getCorrect() === '0' && $foundInStudentsAnswer) { $allcorrect = false; break; } } } if ($allcorrect) { $points = $pro->getExercise()->getMaxPoints(); } // save the marking #region Form to PDF if ($pro->getMarking() === null) { $raw = $pro->getRawSubmission(); $exerciseName = ''; if ($raw !== null) { $exerciseName = $raw->getExerciseName(); } $answer = ""; if ($forms->getType() == 0) { $answer = $formdata->getChoices()[0]->getText(); } if ($forms->getType() == 1) { $answer = $this->ChoiceIdToText($formdata->getChoices()[0]->getText(), $forms->getChoices()); } if ($forms->getType() == 2) { foreach ($formdata->getChoices() as $chosen) { $answer .= $this->ChoiceIdToText($chosen->getText(), $forms->getChoices()) . '<br>'; } } $answer2 = ""; foreach ($forms->getChoices() as $chosen) { if ($chosen->getCorrect() === '1') { $answer2 .= $chosen->getText() . '<br>'; } } $Text = "<h1>AUFGABE {$exerciseName}</h1>" . "<hr>"; if ($forms->getTask() !== null && trim($forms->getTask()) != '') { $Text .= "<p>" . "<h2>Aufgabenstellung:</h2>" . $forms->getTask() . "</p>"; } $Text .= "<p>" . "<h2>Antwort:</h2>" . "<span style=\"color: " . ($points === 0 ? 'red' : 'black') . "\">" . $answer . "</span></p>"; if ($points === 0) { $Text .= "<p>" . "<h2>Lösung:</h2><span style=\"color: green\">" . $answer2 . "</span></p>"; } if ($forms->getSolution() !== null && trim($forms->getSolution()) != '') { $Text .= "<p>" . "<h2>Lösungsbegründung:</h2>" . $forms->getSolution() . "</p>"; } $Text .= "<p style=\"text-align: center;\">" . "<h2><span style=\"color: red\">{$points}P</span></h2>" . "</p>"; $pdf = Pdf::createPdf($Text); //echo Pdf::encodePdf($pdf);return; $result = Request::routeRequest('POST', '/pdf', array(), Pdf::encodePdf($pdf), $this->_pdf, 'pdf'); // checks the correctness of the query if ($result['status'] >= 200 && $result['status'] <= 299) { $pdf = File::decodeFile($result['content']); $pdf->setDisplayName($exerciseName . '.pdf'); $pdf->setTimeStamp($timestamp); $pdf->setBody(null); $submission = $pro->getSubmission(); if ($submission === null) { $submission = $pro->getRawSubmission(); } $studentId = $pro->getRawSubmission() !== null ? $pro->getRawSubmission()->getStudentId() : null; if ($studentId === null) { $studentId = $pro->getSubmission() !== null ? $pro->getSubmission()->getStudentId() : null; } $marking = Marking::createMarking(null, $studentId, null, null, null, null, 3, $points, $submission->getDate() !== null ? $submission->getDate() : time()); if (is_object($submission)) { $marking->setSubmission(clone $submission); } $marking->setFile($pdf); $pro->setMarking($marking); } else { $res[] = null; $this->app->response->setStatus(409); continue; } } #endregion $rawSubmission = $pro->getRawSubmission(); $rawFile = $rawSubmission->getFile(); $rawFile->setBody(Form::encodeForm($formdata), true); $rawSubmission->setFile($rawFile); $rawSubmission->setExerciseId($eid); $pro->setRawSubmission($rawSubmission); $res[] = $pro; continue; } } } $this->app->response->setStatus(409); $res[] = null; } if (!$arr && count($res) == 1) { $this->app->response->setBody(Process::encodeProcess($res[0])); } else { $this->app->response->setBody(Process::encodeProcess($res)); } }
/** * Adds a user's submission to the database and filesystem * * Called then this component receives an HTTP POST request to * /submission(/) * The request body should contain a JSON object representing a submission. * * @author Till Uhlig * @date 2014 */ public function addSubmission() { $body = $this->app->request->getBody(); $submission = Submission::decodeSubmission($body); $file = $submission->getFile(); if (!isset($file) || $file == array()) { $file = new File(); } if ($file->getTimeStamp() === null) { $file->setTimeStamp(time()); } ///echo File::encodeFile($file);return; // upload file to filesystem $result = Request::routeRequest('POST', '/file', array(), File::encodeFile($file), $this->_file, 'file'); ///var_dump($result); ///echo $result['content'];return; if ($result['status'] >= 200 && $result['status'] <= 299) { // file is uploaded $newFile = File::decodeFile($result['content']); $file->setAddress($newFile->getAddress()); $file->setHash($newFile->getHash()); $file->setFileId($newFile->getFileId()); $file->setBody(null); $submission->setFile($file); // upload submission to database if ($submission->getId() === null) { //echo Submission::encodeSubmission($submission);return; $result = Request::routeRequest('POST', '/submission', array(), Submission::encodeSubmission($submission), $this->_submission, 'submission'); } else { $result['status'] = 201; $result['content'] = Submission::encodeSubmission($submission); } //var_dump($result); if ($result['status'] >= 200 && $result['status'] <= 299) { // submission is uploaded $newsubmission = Submission::decodeSubmission($result['content']); $submission->setId($newsubmission->getId()); // select new submission if ($submission->getSelectedForGroup() == '1') { $selectedSubmission = SelectedSubmission::createSelectedSubmission($submission->getLeaderId(), $submission->getId(), $submission->getExerciseId()); $result = Request::routeRequest('POST', '/selectedsubmission', array(), SelectedSubmission::encodeSelectedSubmission($selectedSubmission), $this->_selectedSubmission, 'selectedsubmission'); if ($result['status'] >= 200 && $result['status'] <= 299) { $this->app->response->setBody(Submission::encodeSubmission($submission)); $this->app->response->setStatus(201); $this->app->stop(); } else { $result = Request::routeRequest('PUT', '/selectedsubmission/leader/' . $submission->getLeaderId() . '/exercise/' . $submission->getExerciseId(), $this->app->request->headers->all(), SelectedSubmission::encodeSelectedSubmission($selectedSubmission), $this->_selectedSubmission, 'selectedsubmission'); if ($result['status'] >= 200 && $result['status'] <= 299) { $this->app->response->setBody(Submission::encodeSubmission($submission)); $this->app->response->setStatus(201); $this->app->stop(); } } } else { $this->app->response->setBody(Submission::encodeSubmission($submission)); $this->app->response->setStatus(201); $this->app->stop(); } } } Logger::Log('POST AddSubmission failed', LogLevel::ERROR); $this->app->response->setBody(Submission::encodeSubmission(new Submission())); $this->app->response->setStatus(409); $this->app->stop(); }
/** * Adds a process. * * Called when this component receives an HTTP POST request to * /process(/). */ public function AddProcess() { $this->app->response->setStatus(201); $body = $this->app->request->getBody(); $processes = Process::decodeProcess($body); // always been an array $arr = true; if (!is_array($processes)) { $processes = array($processes); $arr = false; } $res = array(); foreach ($processes as $process) { // create process $method = 'POST'; $URL = '/process'; if ($process->getProcessId() !== null) { $method = 'PUT'; $URL = '/process/' . $process->getProcessId(); } $result = Request::routeRequest($method, $URL, array(), Process::encodeProcess($process), $this->_processorDb, 'process'); if ($result['status'] >= 200 && $result['status'] <= 299) { $queryResult = Process::decodeProcess($result['content']); if ($process->getProcessId() === null) { $process->setProcessId($queryResult->getProcessId()); } $res[] = $process; } else { $res[] = null; $this->app->response->setStatus(409); continue; } // create attachment $attachments = $process->getAttachment(); $process->setAttachment(array()); foreach ($attachments as $attachment) { if ($attachment->getId() === null) { $attachment->setExerciseId($process->getExercise()->getId()); $attachment->setProcessId($process->getProcessId()); // upload file $result = Request::routeRequest('POST', '/file', array(), File::encodeFile($attachment->getFile()), $this->_file, 'file'); if ($result['status'] >= 200 && $result['status'] <= 299) { $queryResult = File::decodeFile($result['content']); $attachment->setFile($queryResult); } else { $attachment->setFile(null); $this->app->response->setStatus(409); continue; } // upload attachment $attachment->setProcessId($process->getProcessId()); $result = Request::routeRequest('POST', '/attachment', array(), Attachment::encodeAttachment($attachment), $this->_attachment, 'attachment'); if ($result['status'] >= 200 && $result['status'] <= 299) { $queryResult = Attachment::decodeAttachment($result['content']); $attachment->setId($queryResult->getId()); $process->getAttachment()[] = $attachment; } else { $process->getAttachment()[] = null; $this->app->response->setStatus(409); continue; } } } // create workFiles $workFiles = $process->getWorkFiles(); $process->setWorkFiles(array()); foreach ($workFiles as $workFile) { if ($workFile->getId() === null) { $workFile->setExerciseId($process->getExercise()->getId()); $workFile->setProcessId($process->getProcessId()); // upload file $result = Request::routeRequest('POST', '/file', array(), File::encodeFile($workFile->getFile()), $this->_file, 'file'); if ($result['status'] >= 200 && $result['status'] <= 299) { $queryResult = File::decodeFile($result['content']); $workFile->setFile($queryResult); } else { $workFile->setFile(null); $this->app->response->setStatus(409); continue; } // upload attachment $workFile->setProcessId($process->getProcessId()); $result = Request::routeRequest('POST', '/attachment', array(), Attachment::encodeAttachment($workFile), $this->_workFiles, 'attachment'); if ($result['status'] >= 200 && $result['status'] <= 299) { $queryResult = Attachment::decodeAttachment($result['content']); $workFile->setId($queryResult->getId()); $process->getWorkFiles()[] = $workFile; } else { $process->getWorkFiles()[] = null; $this->app->response->setStatus(409); continue; } } } } if (!$arr && count($res) == 1) { $this->app->response->setBody(Process::encodeProcess($res[0])); } else { $this->app->response->setBody(Process::encodeProcess($res)); } }
/** * the constructor * * @param $data an assoc array with the object informations */ public function __construct($data = array()) { if ($data === null) { $data = array(); } foreach ($data as $key => $value) { if (isset($key)) { if ($key == 'file') { $this->{$key} = File::decodeFile($value, false); } else { $func = 'set' . strtoupper($key[0]) . substr($key, 1); $methodVariable = array($this, $func); if (is_callable($methodVariable)) { $this->{$func}($value); } else { $this->{$key} = $value; } } } } }
} // attachments if (isset($attachments[$exerciseId])) { foreach ($attachments[$exerciseId] as $attachment) { if (isset($attachment['file']['address'])) { $attachment['file']['displayName'] = "{$namesOfExercises[$exerciseId]}/A_{$attachment['file']['hash']}_{$attachment['file']['displayName']}"; $files[] = $attachment['file']; } } } } } unset($attachments, $markings, $exercises); // sheetFile if (isset($sheet['sheetFile']['address'])) { $sheet['sheetFile']['displayName'] = "{$sheet['sheetFile']['displayName']}"; $files[] = $sheet['sheetFile']; } // sampleSolution if (isset($sheet['sampleSolution']['address'])) { $sheet['sampleSolution']['displayName'] = "{$sheet['sampleSolution']['displayName']}"; $files[] = $sheet['sampleSolution']; } $fileString = json_encode($files); $zipfile = http_post_data($filesystemURI . '/zip', $fileString, true); $zipfile = File::decodeFile($zipfile); $zipfile->setDisplayName('markings.zip'); $zipfile = File::encodeFile($zipfile); echo $zipfile; exit(0); }
/** * Processes a process * * Called when this component receives an HTTP POST request to * /process(/). */ public function postProcess() { $this->app->response->setStatus(201); $header = $this->app->request->headers->all(); $body = $this->app->request->getBody(); $process = Process::decodeProcess($body); // always been an array $arr = true; if (!is_array($process)) { $process = array($process); $arr = false; } // this array contains the indices of the inserted objects $res = array(); foreach ($process as $pro) { $eid = $pro->getExercise()->getId(); // loads the form from database $result = Request::routeRequest('GET', '/form/exercise/' . $eid, $this->app->request->headers->all(), '', $this->_formDb, 'form'); // checks the correctness of the query if ($result['status'] >= 200 && $result['status'] <= 299) { // only one form as result $forms = Form::decodeForm($result['content']); $forms = $forms[0]; $formdata = $pro->getRawSubmission()->getFile(); $timestamp = $formdata->getTimeStamp(); if ($timestamp === null) { $timestamp = time(); } if ($formdata !== null && $forms !== null) { $formdata = Form::decodeForm($formdata->getBody(true)); if (is_array($formdata)) { $formdata = $formdata[0]; } if ($formdata !== null) { // check the submission $fail = false; $parameter = explode(' ', strtolower($pro->getParameter())); $choices = $formdata->getChoices(); if ($forms->getType() == 0) { foreach ($choices as &$choice) { $i = 0; for ($i < 0; $i < count($parameter); $i++) { $param = $parameter[$i]; if ($param === null || $param === '') { continue; } switch ($param) { case 'isnumeric': if (!@preg_match("%^-?([0-9])+([,]([0-9])+)?\$%", DefaultNormalizer::normalizeText($choice->getText()))) { $fail = true; $pro->addMessage('"' . $choice->getText() . '" ist keine gültige Zahl. <br>Bsp.: -0,00'); } break; case 'isdigit': if (!ctype_digit(DefaultNormalizer::normalizeText($choice->getText()))) { $fail = true; $pro->addMessage('"' . $choice->getText() . '" ist keine gültige Ziffernfolge.'); } break; case 'isprintable': if (!ctype_print(DefaultNormalizer::normalizeText($choice->getText()))) { $fail = true; $pro->addMessage('"' . $choice->getText() . '" enthält nicht-druckbare Zeichen.'); } break; case 'isalpha': if (!ctype_alpha(DefaultNormalizer::normalizeText($choice->getText()))) { $fail = true; $pro->addMessage('"' . $choice->getText() . '" ist keine gültige Buchstabenfolge.'); } break; case 'isalphanum': if (!ctype_alnum(DefaultNormalizer::normalizeText($choice->getText()))) { $fail = true; $pro->addMessage('"' . $choice->getText() . '" ist nicht alphanumerisch.'); } break; case 'ishex': if (!ctype_xdigit(DefaultNormalizer::normalizeText($choice->getText()))) { $fail = true; $pro->addMessage('"' . $choice->getText() . '" ist keine gültige Hexadezimalzahl.'); } break; default: $test = $parameter[$i]; $i++; while ($i < count($parameter)) { if (@preg_match($test, DefaultNormalizer::normalizeText($choice->getText())) !== false) { break; } $test .= ' ' . $parameter[$i]; $i++; } $match = @preg_match($test, DefaultNormalizer::normalizeText($choice->getText())); if ($match === false) { $fail = true; $pro->addMessage('"' . $test . '" ist kein gültiger regulärer Ausdruck.'); } elseif ($match == false) { $fail = true; $pro->addMessage('"' . $choice->getText() . '" entspricht nicht dem regulären Ausdruck "' . $test . '".'); } break; } } } } if ($fail) { // received submission isn't correct $pro->setStatus(409); $res[] = $pro; $this->app->response->setStatus(409); continue; } // save the submission #region Form to PDF if ($pro->getSubmission() === null) { $raw = $pro->getRawSubmission(); $exerciseName = ''; if ($raw !== null) { $exerciseName = $raw->getExerciseName(); } $answer = ""; if ($forms->getType() == 0) { $answer = $formdata->getChoices()[0]->getText(); } if ($forms->getType() == 1) { $answer = $this->ChoiceIdToText($formdata->getChoices()[0]->getText(), $forms->getChoices()); } if ($forms->getType() == 2) { foreach ($formdata->getChoices() as $chosen) { $answer .= $this->ChoiceIdToText($chosen->getText(), $forms->getChoices()) . '<br>'; } } $Text = "<h1>AUFGABE {$exerciseName}</h1>" . "<hr>"; if ($forms->getTask() !== null && trim($forms->getTask()) != '') { $Text .= "<p>" . "<h2>Aufgabenstellung:</h2>" . $forms->getTask() . "</p>"; } $Text .= "<p>" . "<h2>Antwort:</h2>" . $answer . "</p>"; $pdf = Pdf::createPdf($Text); $pdf->setText($Text); //echo Pdf::encodePdf($pdf);return; $result = Request::routeRequest('POST', '/pdf', array(), Pdf::encodePdf($pdf), $this->_pdf, 'pdf'); // checks the correctness of the query if ($result['status'] >= 200 && $result['status'] <= 299) { $pdf = File::decodeFile($result['content']); $pdf->setDisplayName($exerciseName . '.pdf'); $pdf->setTimeStamp($timestamp); $pdf->setBody(null); if (is_object($pro->getRawSubmission())) { $submission = clone $pro->getRawSubmission(); } else { $submission = new Submission(); } $submission->setFile($pdf); $submission->setExerciseId($eid); $pro->setSubmission($submission); } else { $pro->setStatus(409); $res[] = $pro; $this->app->response->setStatus(409); continue; } } #endregion $rawSubmission = $pro->getRawSubmission(); $rawFile = $rawSubmission->getFile(); $rawFile->setBody(Form::encodeForm($formdata), true); $rawSubmission->setFile($rawFile); $rawSubmission->setExerciseId($eid); $pro->setRawSubmission($rawSubmission); $pro->setStatus(201); $res[] = $pro; continue; } } } $this->app->response->setStatus(409); $pro->setStatus(409); $res[] = $pro; } if (!$arr && count($res) == 1) { $this->app->response->setBody(Process::encodeProcess($res[0])); } else { $this->app->response->setBody(Process::encodeProcess($res)); } }
/** * Adds an attachment. * * Called when this component receives an HTTP POST request to * /attachment(/). * The request body should contain a JSON object representing the * attachment's attributes. */ public function addAttachment() { $header = $this->app->request->headers->all(); $body = $this->app->request->getBody(); $fileObjects = Attachment::decodeAttachment($body); // always been an array $arr = true; if (!is_array($fileObjects)) { $fileObjects = array($fileObjects); $arr = false; } $res = array(); $files = array(); foreach ($fileObjects as $fileObject) { $files[] = $fileObject->getFile(); } //add the Files $result = Request::routeRequest('POST', '/file', array(), File::encodeFile($files), $this->_postFile, 'file'); $tempFiles = File::decodeFile($result['content']); // checks the correctness of the query if ($result['status'] === 201 && isset($result['content'])) { // upload files $countObjects = count($fileObjects); for ($i = 0; $i < $countObjects; $i++) { if ($tempFiles[$i]->getStatus() === 201) { $fileObjects[$i]->setFile($tempFiles[$i]); if ($files[$i] !== null) { $files[$i]->setStatus(201); } } else { $fileObjects[$i]->setStatus(409); $fileObjects[$i]->addMessage("Die Datei konnte nicht gespeichert werden."); if ($files[$i] !== null) { $files[$i]->setBody(); } } } } else { $this->app->response->setStatus(409); $this->app->response->setBody(Attachment::encodeAttachment(new Attachment())); $this->app->stop(); } // upload attachments $result = Request::routeRequest('POST', '/attachment', array(), Attachment::encodeAttachment($fileObjects), $this->_postAttachment, 'attachment'); if ($result['status'] === 201 && isset($result['content'])) { $tempAttachments = Attachment::decodeAttachment($result['content']); $countObjects = count($fileObjects); for ($i = 0; $i < $countObjects; $i++) { $fileObjects[$i]->setStatus($tempAttachments[$i]->getStatus()); $fileObjects[$i]->addMessages($tempAttachments[$i]->getMessages()); if ($tempAttachments[$i]->getStatus() !== 201) { $fileObjects[$i]->addMessage('Anhang konnte nicht erstellt werden.'); $fileObjects[$i]->getFile()->setBody(); } else { $fileObjects[$i]->setId($tempAttachments[$i]->getId()); } $res[] = $fileObjects[$i]; } } else { $this->app->response->setStatus(409); $this->app->response->setBody(Attachment::encodeAttachment(new Attachment())); $this->app->stop(); } if (!$arr && count($res) == 1) { $res = $res[0]; } $this->app->response->setBody(Attachment::encodeAttachment($res)); $this->app->response->setStatus(201); }
/** * Adds a new marking. * * Called when this component receives an HTTP POST request to * /marking(/). * The request body should contain a JSON object representing the new marking. * * @author Till Uhlig * @date 2014 */ public function addMarking() { $header = $this->app->request->headers->all(); $body = $this->app->request->getBody(); $markings = Marking::decodeMarking($body); $this->app->response->setStatus(201); // always been an array $arr = true; if (!is_array($markings)) { $markings = array($markings); $arr = false; } // this array contains the inserted objects $res = array(); foreach ($markings as $marking) { if ($marking->getDate() === null) { $marking->setDate(time()); } $file = $marking->getFile(); if (!isset($file)) { $file = new File(); } if ($file->getTimeStamp() === null) { $file->setTimeStamp(time()); } // upload file to filesystem $result = Request::routeRequest('POST', '/file', $this->app->request->headers->all(), File::encodeFile($file), $this->_file, 'file'); // checks the correctness of the query if ($result['status'] >= 200 && $result['status'] <= 299) { // file is uploaded $newFile = File::decodeFile($result['content']); $file->setAddress($newFile->getAddress()); $file->setHash($newFile->getHash()); $file->setFileId($newFile->getFileId()); $file->setBody(null); $marking->setFile($file); // upload marking to database if ($marking->getId() === null) { $result = Request::routeRequest('POST', '/marking', $this->app->request->headers->all(), Marking::encodeMarking($marking), $this->_marking, 'marking'); } else { $result = Request::routeRequest('PUT', '/marking/marking/' . $marking->getId(), $this->app->request->headers->all(), Marking::encodeMarking($marking), $this->_marking, 'marking'); } if ($result['status'] >= 200 && $result['status'] <= 299) { // marking is uploaded $newmarking = Marking::decodeMarking($result['content']); if (is_array($newmarking)) { $newmarking = $newmarking[0]; } if ($newmarking->getId() !== null) { $marking->setId($newmarking->getId()); } $res[] = $marking; if (isset($result['headers']['Content-Type'])) { $this->app->response->headers->set('Content-Type', $result['headers']['Content-Type']); } } else { Logger::Log('POST AddMarking failed', LogLevel::ERROR); $this->app->response->setStatus(isset($result['status']) ? $result['status'] : 409); $this->app->response->setBody(Marking::encodeMarking($res)); $this->app->stop(); } } else { Logger::Log('POST AddMarking failed', LogLevel::ERROR); $this->app->response->setStatus(isset($result['status']) ? $result['status'] : 409); $this->app->response->setBody(Marking::encodeMarking($res)); $this->app->stop(); } } if (!$arr && count($res) == 1) { $this->app->response->setBody(Marking::encodeMarking($res[0])); } else { $this->app->response->setBody(Marking::encodeMarking($res)); } }
public static function ExtractFile($data, $singleResult = false) { // generates an assoc array of files by using a defined list of // its attributes $res = DBJson::getResultObjectsByAttributes($data, File::getDBPrimaryKey(), File::getDBConvert()); $res = File::decodeFile($res, false); if ($singleResult == true) { // only one object as result if (count($res) > 0) { $res = $res[0]; } } return $res; }
public function uploadZip($userid, $courseid) { // error array of strings $errors = array(); LTutor::generatepath($this->config['DIR']['temp']); $tempDir = $this->tempdir($this->config['DIR']['temp'], 'extractZip', $mode = 0775); $body = File::decodeFile($this->app->request->getBody()); //1 file-Object $filename = $tempDir . '/' . $courseid . '.zip'; file_put_contents($filename, $body->getBody(true)); unset($body); $zip = new ZipArchive(); $zip->open($filename); $zip->extractTo($tempDir . '/files'); $zip->close(); unlink($filename); ///$this->deleteDir(dirname($filename)); unset($zip); $files = $tempDir . '/files'; // check if csv file exists if (file_exists($files . '/Liste.csv')) { $csv = fopen($files . '/Liste.csv', "r"); if (($transactionId = fgetcsv($csv, 0, ';')) === false) { fclose($csv); $this->deleteDir($tempDir); $this->app->response->setStatus(409); $errors[] = 'empty .csv file'; $this->app->response->setBody(json_encode($errors)); $this->app->stop(); } $result = Request::routeRequest('GET', '/transaction/authentication/TutorCSV_' . $userid . '_' . $courseid . '/transaction/' . $transactionId[0], array(), '', $this->_getTransaction, 'transaction'); if (isset($result['status']) && $result['status'] == 200 && isset($result['content'])) { $transaction = Transaction::decodeTransaction($result['content']); $transaction = json_decode($transaction->getContent(), true); unset($result); $defaultOrder = array('ID', 'NAME', 'USERNAME', 'POINTS', 'MAXPOINTS', 'OUTSTANDING', 'STATUS', 'TUTORCOMMENT', 'STUDENTCOMMENT', 'FILE'); $currectOrder = $defaultOrder; $markings = array(); while (($row = fgetcsv($csv, 0, ';')) !== false) { if (substr($row[0], 0, 2) == '--') { $row[0] = substr($row[0], 2); if (in_array(strtoupper($row[0]), $defaultOrder)) { $currectOrder = array(); foreach ($row as $ro) { $currectOrder[strtoupper($ro)] = count($currectOrder); } } } elseif (implode('', $row) != '' && substr($row[0], 0, 2) != '--') { if (isset($currectOrder['ID']) && !isset($row[$currectOrder['ID']]) || isset($currectOrder['POINTS']) && !isset($row[$currectOrder['POINTS']]) || isset($currectOrder['FILE']) && !isset($row[$currectOrder['FILE']]) || isset($currectOrder['TUTORCOMMENT']) && !isset($row[$currectOrder['TUTORCOMMENT']]) || isset($currectOrder['OUTSTANDING']) && !isset($row[$currectOrder['OUTSTANDING']]) || isset($currectOrder['STATUS']) && !isset($row[$currectOrder['STATUS']])) { $errors[] = 'invalid Liste.csv'; fclose($csv); $this->deleteDir($tempDir); $this->app->response->setStatus(409); $this->app->response->setBody(json_encode($errors)); $this->app->stop(); } $markingId = isset($currectOrder['ID']) ? $row[$currectOrder['ID']] : null; $points = isset($currectOrder['POINTS']) ? $row[$currectOrder['POINTS']] : null; $points = str_replace(',', '.', $points); $markingFile = isset($currectOrder['FILE']) ? $row[$currectOrder['FILE']] : null; // check if markingId exists in transaction if (!isset($transaction['markings'][$markingId])) { // unknown markingId fclose($csv); $this->deleteDir($tempDir); $this->app->response->setStatus(409); $errors[] = "unknown ID: {$markingId}"; $this->app->response->setBody(json_encode($errors)); $this->app->stop(); } ///var_dump($transaction['markings'][$markingId]); $markingData = $transaction['markings'][$markingId]; // checks whether the points are less or equal to the maximum points if ($points > $markingData['maxPoints'] || $points < 0) { // too much points ///fclose($csv); ///$this->deleteDir($tempDir); ///$this->app->response->setStatus(409); ///$errors[] = "incorrect points in marking: {$markingId}"; ///$this->app->response->setBody(json_encode($errors)); ///$this->app->stop(); } // checks if file with this markingid exists if ($markingFile == null || $markingFile == '' || file_exists($files . '/' . $markingFile)) { if ($markingFile != '' && $markingFile != null) { $fileAddress = $files . '/' . $markingFile; ///file_get_contents($files.'/'.$markingFile); // file $fileInfo = pathinfo($markingFile); $file = new File(); $file->setDisplayName($fileInfo['basename']); $file->setBody(Reference::createReference($fileAddress)); } else { $file = null; } if (isset($transaction['markings'][$markingId]['submissionId']) && $transaction['markings'][$markingId]['submissionId'] < 0) { // create new submission object $submissionId = $transaction['markings'][$markingId]['submissionId']; $studentId = $transaction['markings'][$markingId]['studentId']; $exerciseId = $transaction['markings'][$markingId]['exerciseId']; $submission = Submission::createSubmission(null, $studentId, null, $exerciseId, null, 1, time(), null, $leaderId, 1); $submission->setSelectedForGroup('1'); ///echo json_encode($submission);return; $result = Request::routeRequest('POST', '/submission', array(), json_encode($submission), $this->_postSubmission, 'submission'); if ($result['status'] == 201) { $transaction['markings'][$markingId]['submissionId'] = json_decode($result['content'], true)['id']; } } // create new marking object $marking = Marking::createMarking($markingId < 0 ? null : $markingId, $userid, null, $transaction['markings'][$markingId]['submissionId'], isset($currectOrder['TUTORCOMMENT']) ? $row[$currectOrder['TUTORCOMMENT']] : null, isset($currectOrder['OUTSTANDING']) ? $row[$currectOrder['OUTSTANDING']] : null, isset($currectOrder['STATUS']) ? $row[$currectOrder['STATUS']] : null, $points, time(), $file == null ? 1 : 0); $marking->setFile($file); /*array( 'id' => ($markingId<0 ? null : $markingId), 'points' => $points, 'outstanding' => isset($currectOrder['OUTSTANDING']) ? $row[$currectOrder['OUTSTANDING']] : null, 'tutorId' => $userid, 'tutorComment' => isset($currectOrder['TUTORCOMMENT']) ? $row[$currectOrder['TUTORCOMMENT']] : null, 'file' => $file, 'status' => isset($currectOrder['STATUS']) ? $row[$currectOrder['STATUS']] : null, 'date' => time(), 'hideFile' => );*/ $markings[] = $marking; } else { //if file with this markingid not exists $errors[] = 'File does not exist: ' . $markingFile; fclose($csv); $this->deleteDir($tempDir); $this->app->response->setStatus(409); $this->app->response->setBody(json_encode($errors)); $this->app->stop(); } } } $mark = @json_encode($markings); if ($mark !== false) { ///echo json_encode($markings); return; //request to database to edit the markings $result = Request::routeRequest('POST', '/marking', array(), $mark, $this->_postMarking, 'marking'); /// TODO: prüfen ob jede hochgeladen wurde if ($result['status'] != 201) { $errors[] = 'send markings failed'; } } else { $errors[] = 'invalid input'; } } else { $errors[] = 'no transaction data'; } fclose($csv); } else { // if csv file does not exist $errors[] = '.csv file does not exist in uploaded zip-Archiv'; } $this->deleteDir($tempDir); $this->app->response->setBody(json_encode($errors)); if (!($errors == array())) { $this->app->response->setStatus(409); } }
/** * Deletes a file. * * This function handles the reqest to the DBFile table to delete the information * belongs to this file as well as the request * to the filesystem to delete the file. * * @param string $database The link of the database. * @param string $filesystem The link of the filesystem. * @param array $header The header of the request. * @param array $file The file that should being deleted. */ public static function delete($database, $filesystem, $header, $file) { if ($file !== null && $file !== array()) { // requests to file-table of DB $answer = Request::routeRequest('DELETE', '/file/' . $file->getFileId(), $header, '', $database, 'file'); // even if file has been deleted from db file table delete it from fs if ($answer['status'] >= 200 && $answer['status'] <= 299 && isset($answer['content']) && !empty($answer['content'])) { $file = File::decodeFile($answer['content']); if (is_object($file) && $file->getAddress() !== null) { // requests to filesystem $answer = Request::routeRequest('DELETE', '/' . $file->getAddress(), $header, '', $filesystem, 'file'); if ($answer['status'] >= 200 && $answer['status'] <= 299) { return File::decodeFile($answer['content']); } else { return null; } } else { return null; } } else { return $file; } } else { return null; } }
public static function createTests() { LFileTest::$Tester = new Testsystem(); $aufruf = function ($methode, $url, $data) { return Request::custom($methode, 'http://localhost/uebungsplattform/logic/LFile' . $url, array(), $data); }; $auswertungOK = function ($result, $methode, $url, $data, $fileDbGet, $fileDbPost, $fileFsPost) { PHPUnit_Framework_Assert::assertTrue(isset($result['content'])); PHPUnit_Framework_Assert::assertTrue(isset($result['status'])); PHPUnit_Framework_Assert::assertEquals(201, $result['status'], $data); $objData = File::decodeFile($data); $obj = File::decodeFile($result['content']); PHPUnit_Framework_Assert::assertEquals(is_array($objData), is_array($obj)); if (!is_array($obj)) { $obj = array($obj); } if (!is_array($objData)) { $objData = array($objData); } foreach ($obj as $res) { PHPUnit_Framework_Assert::assertEquals(null, $res->getBody()); PHPUnit_Framework_Assert::assertEquals(201, $res->getStatus(), $data); // prüfe Inhalt der Objekte } }; $auswertungWrongSyntax = function ($result, $methode, $url, $data, $fileDbGet, $fileDbPost, $fileFsPost) { PHPUnit_Framework_Assert::assertTrue(isset($result['content'])); PHPUnit_Framework_Assert::assertTrue(isset($result['status'])); PHPUnit_Framework_Assert::assertEquals(201, $result['status'], $data); $objData = File::decodeFile($data); $obj = File::decodeFile($result['content']); PHPUnit_Framework_Assert::assertEquals(is_array($objData), is_array($obj)); if (!is_array($obj)) { $obj = array($obj); } if (!is_array($objData)) { $objData = array($objData); } foreach ($obj as $res) { PHPUnit_Framework_Assert::assertEquals(null, $res->getBody()); PHPUnit_Framework_Assert::assertEquals(409, $res->getStatus(), $data); } }; $filesOK = array('{"fileId":"1_?aÖ","body":"f4","address":"a","hash":"hh"}', '{"body":"f4"}', '[{"fileId":"1_?aÖ","body":"f4","address":"a","hash":"hh"}]'); $filesWrongSyntax = array('{"fileId":"1_?aÖ","body":"f4","address"a}', '[{"fileId":"1_?aÖ","body":"f4","address":"a","hash":"h]', '{"fileId":"1_?aÖ",}', '{"address":"a"}', '{"hash":"hh"}', '{"displayName":"hh"}', '', '[]', '{}', null, array()); LFileTest::$Tester->situationHinzufuegen(new Situation('Funktioniert', $aufruf, $auswertungOK, new Sammlung('Methoden', 'POST'), new Sammlung('URL', '/file'), new Sammlung('Data', $filesOK), new Sammlung('fileDbGet', '{"fileId":"1_?aÖ","address":"a","hash":"hh"}'), new Sammlung('fileDbPost', '{"fileId":"1_?aÖ"}'), new Sammlung('fileFsPost', '{"address":"a","hash":"hh"}'))); LFileTest::$Tester->situationHinzufuegen(new Situation('SyntaxFehlerhaft', $aufruf, $auswertungWrongSyntax, new Sammlung('Methoden', 'POST'), new Sammlung('URL', '/file'), new Sammlung('Data', $filesWrongSyntax), new Sammlung('fileDbGet', null), new Sammlung('fileDbPost', null), new Sammlung('fileFsPost', null))); }
/** * Adds a file. * * Called when this component receives an HTTP DELETE request to * /file/$path(/) * * @param String the path, where the file should be stored */ public function postPathFile($path) { Logger::Log('starts POST postFile', LogLevel::DEBUG); $this->_app->response->setStatus(201); $body = $this->_app->request->getBody(); $fileObjects = File::decodeFile($body); if (!is_array($path)) { $path = array($path); } $temp = ""; foreach ($path as $part) { if ($part != '') { $temp .= $part . '/'; } } $path = $temp; // always been an array $arr = true; if (!is_array($fileObjects)) { $fileObjects = array($fileObjects); $arr = false; } $res = array(); foreach ($fileObjects as $fileObject) { if ($fileObject->getBody() == null && $fileObject->getAddress() == null) { $result = new File(); $result->setBody(null); $result->setStatus(409); $res[] = $result; continue; } $result = LFileHandler2::add($this->_db, $this->_fs, $path, array(), $fileObject); if ($result !== null) { $result->setStatus(201); $result->setBody(null); $res[] = $result; } else { $result = $fileObject; $result->setBody(null); $result->setStatus(409); $result->addMessage("Die Datei konnte nicht gespeichert werden."); $res[] = $result; Logger::Log('POST postPathFile failed', LogLevel::ERROR); } } if (!$arr && count($res) == 1) { $res = $res[0]; } $this->_app->response->setBody(File::encodeFile($res)); }