/**
  * Gets the test session for a particular deliveryExecution
  *
  * @param DeliveryExecution $deliveryExecution
  * @return \qtism\runtime\tests\AssessmentTestSession
  * @throws \common_exception_Error
  * @throws \common_exception_MissingParameter
  */
 public function getTestSession(DeliveryExecution $deliveryExecution)
 {
     if (!isset($this->cache[$deliveryExecution->getIdentifier()]['session'])) {
         $resultServer = \taoResultServer_models_classes_ResultServerStateFull::singleton();
         $compiledDelivery = $deliveryExecution->getDelivery();
         $inputParameters = $this->getRuntimeInputParameters($deliveryExecution);
         $testDefinition = \taoQtiTest_helpers_Utils::getTestDefinition($inputParameters['QtiTestCompilation']);
         $testResource = new \core_kernel_classes_Resource($inputParameters['QtiTestDefinition']);
         $sessionManager = new \taoQtiTest_helpers_SessionManager($resultServer, $testResource);
         $userId = $deliveryExecution->getUserIdentifier();
         $qtiStorage = new \taoQtiTest_helpers_TestSessionStorage($sessionManager, new BinaryAssessmentTestSeeker($testDefinition), $userId);
         $sessionId = $deliveryExecution->getIdentifier();
         if ($qtiStorage->exists($sessionId)) {
             $session = $qtiStorage->retrieve($testDefinition, $sessionId);
             if ($session instanceof UserUriAware) {
                 $session->setUserUri($userId);
             }
             $resultServerUri = $compiledDelivery->getOnePropertyValue(new \core_kernel_classes_Property(TAO_DELIVERY_RESULTSERVER_PROP));
             $resultServerObject = new \taoResultServer_models_classes_ResultServer($resultServerUri, array());
             $resultServer->setValue('resultServerUri', $resultServerUri->getUri());
             $resultServer->setValue('resultServerObject', array($resultServerUri->getUri() => $resultServerObject));
             $resultServer->setValue('resultServer_deliveryResultIdentifier', $deliveryExecution->getIdentifier());
         } else {
             $session = null;
         }
         $this->cache[$deliveryExecution->getIdentifier()] = ['session' => $session, 'storage' => $qtiStorage];
     }
     return $this->cache[$deliveryExecution->getIdentifier()]['session'];
 }
 /**
  * (non-PHPdoc)
  * @see tao_models_classes_export_ExportHandler::export()
  */
 public function export($formValues, $destination)
 {
     $file = null;
     if (isset($formValues['filename']) === true) {
         $instances = is_string($formValues['instances']) ? array($formValues['instances']) : $formValues['instances'];
         if (count($instances) > 0) {
             $fileName = $formValues['filename'] . '_' . time() . '.zip';
             $path = tao_helpers_File::concat(array($destination, $fileName));
             if (tao_helpers_File::securityCheck($path, true) === false) {
                 throw new common_Exception('Unauthorized file name for QTI Test ZIP archive.');
             }
             // Create a new ZIP archive to store data related to the QTI Test.
             $zip = new ZipArchive();
             if ($zip->open($path, ZipArchive::CREATE) !== true) {
                 throw new common_Exception("Unable to create ZIP archive for QTI Test at location '" . $path . "'.");
             }
             // Create an empty IMS Manifest as a basis.
             $manifest = taoQtiTest_helpers_Utils::emptyImsManifest();
             foreach ($instances as $instance) {
                 $testResource = new core_kernel_classes_Resource($instance);
                 $testExporter = new taoQtiTest_models_classes_export_QtiTestExporter($testResource, $zip, $manifest);
                 common_Logger::d('Export ' . $instance);
                 $testExporter->export();
             }
             $file = $path;
             $zip->close();
         } else {
             common_Logger::w("No instance in form to export");
         }
     } else {
         common_Logger::w("Missing filename for QTI Test export using Export Handler '" . __CLASS__ . "'.");
     }
     return $file;
 }
 /**
  * Action to finish test attempts where the maximum time limit has been reached.
  * To end user will be sent array that contains id's of finished session.
  */
 public function endExpiredTests()
 {
     $started = \taoDelivery_models_classes_DeliveryServerService::singleton()->getResumableDeliveries();
     $resultServer = \taoResultServer_models_classes_ResultServerStateFull::singleton();
     $result = array();
     foreach ($started as $deliveryExecution) {
         $compiledDelivery = $deliveryExecution->getDelivery();
         $runtime = \taoDelivery_models_classes_DeliveryAssemblyService::singleton()->getRuntime($compiledDelivery);
         $inputParameters = \tao_models_classes_service_ServiceCallHelper::getInputValues($runtime, array());
         $testDefinition = \taoQtiTest_helpers_Utils::getTestDefinition($inputParameters['QtiTestCompilation']);
         $testResource = new \core_kernel_classes_Resource($inputParameters['QtiTestDefinition']);
         $subjectProp = new \core_kernel_classes_Property(PROPERTY_DELVIERYEXECUTION_SUBJECT);
         $delvieryExecutionSubject = $deliveryExecution->getOnePropertyValue($subjectProp);
         $sessionManager = new \taoQtiTest_helpers_SessionManager($resultServer, $testResource);
         $qtiStorage = new \taoQtiTest_helpers_TestSessionStorage($sessionManager, new BinaryAssessmentTestSeeker($testDefinition), $delvieryExecutionSubject->getUri());
         $session = $qtiStorage->retrieve($testDefinition, $deliveryExecution->getUri());
         $resultServerUri = $compiledDelivery->getOnePropertyValue(new \core_kernel_classes_Property(TAO_DELIVERY_RESULTSERVER_PROP));
         $resultServerObject = new \taoResultServer_models_classes_ResultServer($resultServerUri, array());
         $resultServer->setValue('resultServerUri', $resultServerUri->getUri());
         $resultServer->setValue('resultServerObject', array($resultServerUri->getUri() => $resultServerObject));
         $resultServer->setValue('resultServer_deliveryResultIdentifier', $deliveryExecution->getUri());
         if ($session->isRunning() === false) {
             continue;
         }
         try {
             $session->checkTimeLimits(false, false, false);
         } catch (AssessmentTestSessionException $e) {
             if (AssessmentTestSessionException::ASSESSMENT_TEST_DURATION_OVERFLOW) {
                 $testSessionMetaData = new TestSessionMetaData($session);
                 $testSessionMetaData->save(array('TEST' => array('TEST_EXIT_CODE' => TestSessionMetaData::TEST_CODE_INCOMPLETE), 'SECTION' => array('SECTION_EXIT_CODE' => TestSessionMetaData::SECTION_CODE_TIMEOUT)));
                 $session->endTestSession();
                 $deliveryExecution->setState(INSTANCE_DELIVERYEXEC_FINISHED);
                 \common_Logger::i("Expired test session {$session->getSessionId()} has finished.");
                 $result[] = $session->getSessionId();
             }
         }
     }
     echo json_encode($result);
 }
 protected function createManifest()
 {
     return taoQtiTest_helpers_Utils::emptyImsManifest('2.1');
 }
 /**
  * Imports the auxiliary files (file elements contained in the resource test element to be imported) into
  * the TAO Test Content directory.
  *
  * If some file cannot be copied, warnings will be committed.
  *
  * @param core_kernel_file_File $testContent The pointer to the TAO Test Content directory where auxilliary files will be stored.
  * @param oat\taoQtiItem\model\qti\Resource $qtiResource The manifest resource describing the test to be imported.
  * @param string $extractionFolder The absolute path to the temporary folder containing the content of the imported IMS QTI Package Archive.
  * @param common_report_Report A report about how the importation behaved.
  */
 protected function importTestAuxiliaryFiles(core_kernel_file_File $testContent, Resource $qtiResource, $extractionFolder, common_report_Report $report)
 {
     foreach ($qtiResource->getAuxiliaryFiles() as $aux) {
         try {
             taoQtiTest_helpers_Utils::storeQtiResource($testContent, $aux, $extractionFolder);
         } catch (common_Exception $e) {
             $report->add(new common_report_Report(common_report_Report::TYPE_WARNING, __('Auxiliary file not found at location "%s".', $aux)));
         }
     }
 }
 /**
  * Retrieve the Test Definition the test session is built
  * from as an AssessmentTest object. This method
  * also retrieves the compilation directory.
  * 
  * @param string $qtiTestCompilation (e.g. <i>'http://sample/first.rdf#i14363448108243883-|http://sample/first.rdf#i14363448109065884+'</i>)
  * 
  * @return AssessmentTest The AssessmentTest object the current test session is built from.
  */
 protected function retrieveTestDefinition($qtiTestCompilation)
 {
     $directoryIds = explode('|', $qtiTestCompilation);
     $directories = array('private' => $this->getDirectory($directoryIds[0]), 'public' => $this->getDirectory($directoryIds[1]));
     $this->setCompilationDirectory($directories);
     $testDefinition = \taoQtiTest_helpers_Utils::getTestDefinition($qtiTestCompilation);
     $this->setTestDefinition($testDefinition);
 }
 /**
  * Get rubric to be printed
  * Rubric is considered printed if it included to the section which has an item tagged by specified tag
  * (@see )
  *
  * @param \taoDelivery_models_classes_execution_DeliveryExecution $deliveryExecution
  * @return string
  */
 public function getPrintableRubric(\taoDelivery_models_classes_execution_DeliveryExecution $deliveryExecution)
 {
     $testSessionService = ServiceManager::getServiceManager()->get(TestSessionService::SERVICE_ID);
     $session = $testSessionService->getTestSession($deliveryExecution);
     $inputParameters = $testSessionService->getRuntimeInputParameters($deliveryExecution);
     $testDefinition = \taoQtiTest_helpers_Utils::getTestDefinition($inputParameters['QtiTestCompilation']);
     $sections = $testDefinition->getComponentsByClassName('assessmentSection');
     $tag = $this->getOption(self::OPTION_PRINTABLE_RUBRIC_TAG);
     $directoryIds = explode('|', $inputParameters['QtiTestCompilation']);
     $compilationDirs = array('private' => \tao_models_classes_service_FileStorage::singleton()->getDirectoryById($directoryIds[0]), 'public' => \tao_models_classes_service_FileStorage::singleton()->getDirectoryById($directoryIds[1]));
     $rubrics = [];
     // -- variables used in the included rubric block templates.
     // base path (base URI to be used for resource inclusion).
     $basePathVarName = TAOQTITEST_BASE_PATH_NAME;
     ${$basePathVarName} = $compilationDirs['public']->getPublicAccessUrl();
     // state name (the variable to access to get the state of the assessmentTestSession).
     $stateName = TAOQTITEST_RENDERING_STATE_NAME;
     ${$stateName} = $session;
     // views name (the variable to be accessed for the visibility of rubric blocks).
     $viewsName = TAOQTITEST_VIEWS_NAME;
     ${$viewsName} = array(View::CANDIDATE);
     foreach ($sections as $section) {
         $assessmentItemsRef = $section->getComponentsByClassName('assessmentItemRef');
         foreach ($assessmentItemsRef as $item) {
             foreach ($item->getCategories() as $category) {
                 if ($category === $tag) {
                     foreach ($section->getRubricBlockRefs() as $rubric) {
                         ob_start();
                         include $compilationDirs['private']->getPath() . $rubric->getHref();
                         $rubrics[] = ob_get_clean();
                     }
                 }
             }
         }
     }
     return $rubrics;
 }
 /**
  * Loads the test definition
  */
 protected function initTestDefinition()
 {
     $this->testDefinition = \taoQtiTest_helpers_Utils::getTestDefinition($this->getTestCompilationUri());
 }
 /**
  * Copy the test resources (e.g. images) that will be availabe at delivery time
  * in the public compilation directory.
  * 
  */
 protected function copyPublicResources()
 {
     $compiledDocDir = $this->getPrivateDirectory()->getPath();
     $publicCompiledDocDir = $this->getPublicDirectory()->getPath();
     foreach (tao_helpers_File::scandir($compiledDocDir, array('recursive' => true, 'only' => tao_helpers_File::$FILE, 'absolute' => true)) as $file) {
         $mime = tao_helpers_File::getMimeType($file, true);
         $pathinfo = pathinfo($file);
         // Exclude CSS files because already copied when dealing with rubric blocks.
         if (in_array($mime, self::getPublicMimeTypes()) === true && $pathinfo['extension'] !== 'php') {
             $file = str_replace($compiledDocDir, '', $file);
             common_Logger::t("Copying public resource '{$file}'...");
             taoQtiTest_helpers_Utils::storeQtiResource($publicCompiledDocDir, $file, $compiledDocDir);
         }
     }
 }