/** * (non-PHPdoc) * @see \oat\tao\model\media\MediaBrowser::download() */ public function download($link) { $url = str_replace('\\/', '/', $link); $fileName = \tao_helpers_File::createTempDir() . basename($link); common_Logger::d('Downloading ' . $url); helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::NO_TIMEOUT); $fp = fopen($fileName, 'w+'); $curlHandler = curl_init(); curl_setopt($curlHandler, CURLOPT_URL, $url); curl_setopt($curlHandler, CURLOPT_FILE, $fp); curl_setopt($curlHandler, CURLOPT_TIMEOUT, 50); curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, true); //if there is an http auth on the local domain, it's mandatory to auth with curl if (USE_HTTP_AUTH) { $addAuth = false; $domains = array('localhost', '127.0.0.1', ROOT_URL); foreach ($domains as $domain) { if (preg_match("/" . preg_quote($domain, '/') . "/", $url)) { $addAuth = true; } } if ($addAuth) { curl_setopt($curlHandler, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curlHandler, CURLOPT_USERPWD, USE_HTTP_USER . ":" . USE_HTTP_PASS); } } curl_exec($curlHandler); $httpCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); $success = $httpCode == 200; curl_close($curlHandler); fclose($fp); helpers_TimeOutHelper::reset(); return $fileName; }
/** * Generate a new Booklet from a specific test * in a specific class and return a report * * @param core_kernel_classes_Resource $test * @param core_kernel_classes_Class $class * @return common_report_Report */ public static function generate(core_kernel_classes_Resource $test, core_kernel_classes_Class $class) { $report = new common_report_Report(common_report_Report::TYPE_SUCCESS); $model = \taoTests_models_classes_TestsService::singleton()->getTestModel($test); if ($model->getUri() != INSTANCE_TEST_MODEL_QTI) { $report->setType(common_report_Report::TYPE_ERROR); $report->setMessage(__('%s is not a QTI test', $test->getLabel())); return $report; } // generate file content $tmpFolder = \tao_helpers_File::createTempDir(); $tmpFile = $tmpFolder . 'test.txt'; $content = ''; foreach (self::getItems($test) as $item) { $content .= self::renderItem($item); } file_put_contents($tmpFile, $content); // generate tao instance $instance = BookletClassService::singleton()->createBookletInstance($class, __('%s Booklet', $test->getLabel()), $tmpFile); \tao_helpers_File::delTree($tmpFolder); // return report with instance $report->setMessage(__('%s created', $instance->getLabel())); $report->setData($instance); return $report; }
/** * Gets the rubrics according to the current session state * The content is directly rendered into the page * @param RunnerServiceContext $context * @return mixed */ public function getRubrics(RunnerServiceContext $context) { // TODO: make a better implementation for rubrics loading. /* @var AssessmentTestSession $session */ $session = $context->getTestSession(); $compilationDirs = $context->getCompilationDirectory(); // -- 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); ob_start(); foreach ($session->getRoute()->current()->getRubricBlockRefs() as $rubric) { $data = $compilationDirs['private']->read($rubric->getHref()); $tmpFile = \tao_helpers_File::createTempDir() . basename($rubric->getHref()); file_put_contents($tmpFile, $data); include $tmpFile; unlink($tmpFile); } $rubrics = ob_get_contents(); ob_end_clean(); return $rubrics; }
public function testDeepCloneTriplesFile() { /** @var \core_kernel_versioning_Repository $repository */ $repository = \tao_models_classes_FileSourceService::singleton()->addLocalSource("repository test", \tao_helpers_File::createTempDir()); //see if clone item content works /** @var \core_kernel_versioning_File $file */ $file = $repository->spawnFile(__DIR__ . '/sample/test.xml', "test", function ($originalName) { return md5($originalName); }); //see if clone file works $rdfsTriple = new \core_kernel_classes_Triple(); $rdfsTriple->predicate = "http://www.w3.org/1999/02/22-rdf-syntax-ns#value"; $rdfsTriple->object = $file->getUri(); $return = CloneHelper::deepCloneTriples(array($rdfsTriple)); $this->assertCount(1, $return); $this->assertEquals($rdfsTriple->predicate, $return[0]->predicate); $this->assertNotEquals($rdfsTriple->object, $return[0]->object); $fileCopy = new \core_kernel_file_File($return[0]->object); $this->assertFileExists($fileCopy->getAbsolutePath()); $this->assertEquals($file->getLabel(), $fileCopy->getLabel()); $this->assertNotEquals($file->getAbsolutePath(), $fileCopy->getAbsolutePath()); $file->delete(true); $fileCopy->delete(true); $repository->delete(true); }
public static function importDelivery(core_kernel_classes_Class $deliveryClass, $archiveFile) { $folder = tao_helpers_File::createTempDir(); $zip = new ZipArchive(); if ($zip->open($archiveFile) === true) { if ($zip->extractTo($folder)) { $returnValue = $folder; } $zip->close(); } $manifestPath = $folder . self::MANIFEST_FILE; if (!file_exists($manifestPath)) { return common_report_Report::createFailure(__('Manifest not found in assembly')); } $manifest = json_decode(file_get_contents($manifestPath), true); $label = $manifest['label']; $serviceCall = tao_models_classes_service_ServiceCall::fromString(base64_decode($manifest['runtime'])); $dirs = $manifest['dir']; $resultServer = taoResultServer_models_classes_ResultServerAuthoringService::singleton()->getDefaultResultServer(); try { foreach ($dirs as $id => $relPath) { tao_models_classes_service_FileStorage::singleton()->import($id, $folder . $relPath); } $delivery = $deliveryClass->createInstanceWithProperties(array(RDFS_LABEL => $label, PROPERTY_COMPILEDDELIVERY_DIRECTORY => array_keys($dirs), PROPERTY_COMPILEDDELIVERY_TIME => time(), PROPERTY_COMPILEDDELIVERY_RUNTIME => $serviceCall->toOntology(), TAO_DELIVERY_RESULTSERVER_PROP => $resultServer)); $report = common_report_Report::createSuccess(__('Delivery "%s" successfully imported', $label), $delivery); } catch (Exception $e) { if (isset($delivery) && $delivery instanceof core_kernel_classes_Resource) { $delivery->delete(); } $report = common_report_Report::createFailure(__('Unkown error during impoort')); } return $report; }
public function importDelivery(core_kernel_classes_Class $deliveryClass, $archiveFile) { $folder = tao_helpers_File::createTempDir(); $zip = new ZipArchive(); if ($zip->open($archiveFile) !== true) { return common_report_Report::createFailure(__('Unable to export Archive')); } $zip->extractTo($folder); $zip->close(); $manifestPath = $folder . self::MANIFEST_FILE; if (!file_exists($manifestPath)) { return common_report_Report::createFailure(__('Manifest not found in assembly')); } $manifest = json_decode(file_get_contents($manifestPath), true); try { $this->importDeliveryFiles($deliveryClass, $manifest, $folder); $delivery = $this->importDeliveryResource($deliveryClass, $manifest); $report = common_report_Report::createSuccess(__('Delivery "%s" successfully imported', $delivery->getUri()), $delivery); } catch (Exception $e) { common_Logger::w($e->getMessage()); if (isset($delivery) && $delivery instanceof core_kernel_classes_Resource) { $delivery->delete(); } $report = common_report_Report::createFailure(__('Unkown error during impoort')); } return $report; }
public function testCompile() { //test with items $config = array('previous' => true); $items = array($this->item->getUri()); $this->testModel->save($this->test, array('itemUris' => $items, 'config' => $config)); $waitingReport = new \common_report_Report(\common_report_Report::TYPE_SUCCESS); $serviceCall = $this->getMockBuilder('tao_models_classes_service_ServiceCall')->disableOriginalConstructor()->setMethods(array('serializeToString'))->getMock(); $serviceCall->expects($this->once())->method('serializeToString')->willReturn('greatString'); $waitingReport->setData($serviceCall); $testCompiler = $this->getMockBuilder('oat\\taoTestLinear\\model\\TestCompiler')->setConstructorArgs(array($this->test, $this->storage))->setMethods(array('subCompile', 'spawnPrivateDirectory'))->getMock(); $testCompiler->expects($this->once())->method('subCompile')->willReturn($waitingReport); //will spawn a new directory and store the content file $directoryMock = $this->getMockBuilder('tao_models_classes_service_StorageDirectory')->disableOriginalConstructor()->setMethods(array('getPath'))->getMock(); $tmpDir = \tao_helpers_File::createTempDir(); $this->assertFileExists($tmpDir); $directoryMock->expects($this->once())->method('getPath')->willReturn($tmpDir); $testCompiler->expects($this->once())->method('spawnPrivateDirectory')->willReturn($directoryMock); $report = $testCompiler->compile(); $this->assertEquals(__('Test Compilation'), $report->getMessage(), __('Compilation should work')); $this->assertFileExists($tmpDir . 'data.json', __('Compilation file not created')); $compile = '{"items":{"http:\\/\\/myFancyDomain.com\\/myGreatResourceUriForItem":"greatString"},"previous":true}'; $this->assertEquals($compile, file_get_contents($tmpDir . 'data.json', __('File content error'))); \tao_helpers_File::delTree($tmpDir); $this->assertFileNotExists($tmpDir); }
public function testStoreData() { $store = new DataStorage($this->sentData); $this->sampleFilePath = \tao_helpers_File::createTempDir() . 'stored.csv'; $ref = new \ReflectionProperty('oat\\taoClientDiagnostic\\model\\DataStorage', 'filePath'); $ref->setAccessible(true); $ref->setValue($store, $this->sampleFilePath); $store->setIsCompatible(true)->storeData(); $this->assertFileExists($this->sampleFilePath); $row = 0; if (($handle = fopen($this->sampleFilePath, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { $num = count($data); $row++; $this->assertEquals(24, $num); if ($row === 2) { $this->assertEquals($this->sentData['key'], $data[0]); $this->assertEquals($this->sentData['login'], $data[1]); $this->assertEquals($this->sentData['ip'], $data[2]); $this->assertEquals($this->sentData['browser'], $data[3]); $this->assertEquals($this->sentData['browserVersion'], $data[4]); $this->assertEquals($this->sentData['os'], $data[5]); $this->assertEquals($this->sentData['osVersion'], $data[6]); $this->assertEquals(1, $data[23]); } } fclose($handle); $this->assertEquals(2, $row); } $store->setIsCompatible(false)->storeData(); $row = 0; if (($handle = fopen($this->sampleFilePath, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { $num = count($data); $row++; $this->assertEquals(24, $num); if ($row === 2) { $this->assertEquals($this->sentData['key'], $data[0]); $this->assertEquals($this->sentData['login'], $data[1]); $this->assertEquals($this->sentData['ip'], $data[2]); $this->assertEquals($this->sentData['browser'], $data[3]); $this->assertEquals($this->sentData['browserVersion'], $data[4]); $this->assertEquals($this->sentData['os'], $data[5]); $this->assertEquals($this->sentData['osVersion'], $data[6]); $this->assertEquals(0, $data[23]); } } fclose($handle); $this->assertEquals(2, $row); } return $store; }
public function testDeepDeleteTriples() { //create resources $repository = \tao_models_classes_FileSourceService::singleton()->addLocalSource("Label Test", \tao_helpers_File::createTempDir()); $file = $repository->createFile("test.xml", "sample"); //delete resource DeleteHelper::deepDeleteTriples($file->getRdfTriples()); DeleteHelper::deepDeleteTriples($repository->getRdfTriples()); //see if all is deleted //try to get the resource $resourceTest = new \core_kernel_classes_Resource($repository->getUri()); $fileTest = new \core_kernel_classes_Resource($file->getUri()); $this->assertCount(0, $resourceTest->getRdfTriples()); $this->assertCount(0, $fileTest->getRdfTriples()); }
public function testTracing() { $events = array('{"name":"div","type":"click","time":"1288780765981","id":"qunit-fixture"}', '{"name":"BUSINESS","type":"TEST","time":"1288780765982","id":"12"}', '{"name":"h2","type":"click","time":"1288780766000","id":"qunit-banner"}', '{"name":"h1","type":"click","time":"1288780765999","id":"qunit-header"}'); $folder = tao_helpers_File::createTempDir(); $processId = '123456789'; $eventFilter = $this->eventsService->getEventList($this->eventFile, 'server'); $this->assertTrue($this->eventsService->traceEvent($events, $processId, $folder, $eventFilter)); $this->assertTrue($this->eventsService->traceEvent($events, $processId, $folder)); $this->assertTrue(file_exists($folder . '/' . $processId . '_0.xml')); foreach (glob($folder . '/' . $processId . '*') as $trace_file) { if (preg_match('/(xml|lock)$/', $trace_file)) { unlink($trace_file); } } tao_helpers_File::delTree($folder); }
public function __construct() { $this->tmpDir = \tao_helpers_File::createTempDir(); $this->dir = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__DIR__)); $this->taoDir = dirname($this->dir) . '/tao'; $this->assetDir = $this->dir . '/fontConversion/assets'; $this->doNotEdit = file_get_contents($this->assetDir . '/do-not-edit.tpl'); $this->currentSelection = $this->assetDir . '/selection.json'; $writables = array($this->taoDir . '/views/css/font/tao/', $this->taoDir . '/views/scss/inc/fonts/', $this->taoDir . '/views/js/lib/ckeditor/skins/tao/scss/inc/', $this->taoDir . '/helpers/', $this->assetDir); foreach ($writables as $writable) { if (!is_writable($writable)) { throw new \Exception(implode("\n<br>", $writables) . ' must be writable'); } } $this->setData('icon-listing', $this->loadIconListing()); }
/** * Extract zip package into temp directory * * @param string $source Zip path * @return string Tmp directory to find extracted zip * @throws PortableElementExtractException */ public function extract($source) { $tmpDirectory = null; $this->assertSourceAsFile($source); $folder = \tao_helpers_File::createTempDir(); $zip = new ZipArchive(); if ($zip->open($source) === true) { if ($zip->extractTo($folder)) { $tmpDirectory = $folder; } $zip->close(); } if (!is_dir($tmpDirectory)) { throw new PortableElementExtractException('Unable to extract portable element.'); } return $tmpDirectory; }
public function testStoreFileValid() { $tmpDir = \tao_helpers_File::createTempDir(); $storageDir = $tmpDir . 'media/'; mkdir($storageDir); //force baseDir $ref = new \ReflectionProperty('oat\\taoMediaManager\\model\\fileManagement\\SimpleFileManagement', 'baseDir'); $ref->setAccessible(true); $ref->setValue($this->fileManagement, $storageDir); $ref->setAccessible(false); $fileTmp = dirname(__DIR__) . '/sample/Brazil.png'; $this->assertFileNotExists($storageDir . 'Brazil.png', 'The file is already stored'); $link = $this->fileManagement->storeFile($fileTmp, 'brazil.png'); // test the return link $this->assertInternalType('string', $link, 'The method return should be a string'); $this->assertEquals('brazil.png', $link, 'The link is wrong'); $this->assertFileExists($storageDir . 'brazil.png', 'The file has not been stored'); return array($storageDir, $link); }
public function testSend() { $testfolder = tao_helpers_File::createTempDir(); $expectedFilePath = $testfolder . 'testidentifier' . DIRECTORY_SEPARATOR . 'message.html'; $this->assertFileNotExists($expectedFilePath); $userMock = $this->prophesize('oat\\oatbox\\user\\User'); $userMock->getIdentifier()->willReturn('testidentifier'); $userMock->getIdentifier()->should(new CallTimesPrediction(1)); $messageMock = $this->prophesize('oat\\tao\\model\\messaging\\Message'); $messageMock->getTo()->willReturn($userMock->reveal()); $messageMock->getTo()->should(new CallTimesPrediction(1)); $messageMock->getBody()->willReturn('testBody'); $messageMock->getBody()->should(new CallTimesPrediction(1)); $transporter = new FileSink(array(FileSink::CONFIG_FILEPATH => $testfolder)); $result = $transporter->send($messageMock->reveal()); $this->assertTrue($result); $this->assertFileExists($expectedFilePath); $messageContent = file_get_contents($expectedFilePath); $this->assertEquals('testBody', $messageContent); $userMock->checkProphecyMethodsPredictions(); $messageMock->checkProphecyMethodsPredictions(); tao_helpers_File::delTree($testfolder); $this->assertFalse(is_dir($testfolder)); }
/** * @dataProvider sharedStimulusImportProvider */ public function testEdit($filename, $expectedReport, $called) { if (file_exists($filename)) { $tmpDir = \tao_helpers_File::createTempDir(); copy($filename, $tmpDir . basename($filename)); $filename = $tmpDir . basename($filename); } $clazz = new \core_kernel_classes_Class('http://www.tao.lu/Ontologies/TAOMedia.rdf#Media'); $instance = $clazz->createInstance('my Label'); $file['uploaded_file'] = $filename; $file['name'] = basename($filename); $form = new FileImportForm($instance->getUri()); $form = $form->getForm(); $form->setValues(array('source' => $file, 'lang' => 'EN_en')); if ($called) { $this->service->expects($this->once())->method('editMediaInstance')->willReturn(true); } $report = $this->packageImporter->edit($instance, $form); /** @var \common_report_Report $expectedReport*/ $expectedReport->setMessage(preg_replace('/%s/', 'edited', $expectedReport->getMessage())); $this->assertEquals($expectedReport->getMessage(), $report->getMessage(), __('Report message is wrong')); $this->assertEquals($expectedReport->getType(), $report->getType(), __('Report should be success')); $instance->delete(true); }
public function testEditXml() { $instance = new \core_kernel_classes_Resource('http://fancyDomain.com/tao.rdf#fancyInstanceUri'); $sharedImporter = new SharedStimulusImporter($instance->getUri()); $filename = dirname(__DIR__) . '/sample/sharedStimulus/sharedStimulus.xml'; $tmpDir = \tao_helpers_File::createTempDir(); copy($filename, $tmpDir . basename($filename)); $filename = $tmpDir . basename($filename); $finalFilename = $tmpDir . 'sharedStimulus.xhtml'; $myClass = new \core_kernel_classes_Class('http://fancyDomain.com/tao.rdf#fancyUri'); $info = finfo_open(FILEINFO_MIME_TYPE); $file['type'] = finfo_file($info, $filename); finfo_close($info); $file['uploaded_file'] = $filename; $file['name'] = $filename; $form = $sharedImporter->getForm(); $form->setValues(array('source' => $file, 'lang' => 'EN_en')); $this->service->expects($this->once())->method('editMediaInstance')->with($finalFilename, $instance->getUri(), 'EN_en')->willReturn(true); $report = $sharedImporter->import($myClass, $form); $this->assertEquals(__('Shared Stimulus edited successfully'), $report->getMessage(), __('Report message is wrong')); $this->assertEquals(\common_report_Report::TYPE_SUCCESS, $report->getType(), __('Report should be success')); }
/** * Build the context of the given candidate test $session as an associative array. This array * is especially usefull to transmit the test context to a view as JSON data. * * The returned array contains the following keys: * * * state: The state of test session. * * navigationMode: The current navigation mode. * * submissionMode: The current submission mode. * * remainingAttempts: The number of remaining attempts for the current item. * * isAdaptive: Whether or not the current item is adaptive. * * itemIdentifier: The identifier of the current item. * * itemSessionState: The state of the current assessment item session. * * timeConstraints: The time constraints in force. * * testTitle: The title of the test. * * testPartId: The identifier of the current test part. * * sectionTitle: The title of the current section. * * numberItems: The total number of items eligible to the candidate. * * numberCompleted: The total number items considered to be completed by the candidate. * * moveForwardUrl: The URL to be dereferenced to perform a moveNext on the session. * * moveBackwardUrl: The URL to be dereferenced to perform a moveBack on the session. * * skipUrl: The URL to be dereferenced to perform a skip on the session. * * commentUrl: The URL to be dereferenced to leave a comment about the current item. * * timeoutUrl: The URL to be dereferenced when the time constraints in force reach their maximum. * * canMoveBackward: Whether or not the candidate is allowed/able to move backward. * * jumps: The possible jumpers the candidate is allowed to undertake among eligible items. * * itemServiceApiCall: The JavaScript code to be executed to instantiate the current item. * * rubrics: The XHTML compiled content of the rubric blocks to be displayed for the current item if any. * * allowComment: Whether or not the candidate is allowed to leave a comment about the current item. * * allowSkipping: Whether or not the candidate is allowed to skip the current item. * * considerProgress: Whether or not the test driver view must consider to give a test progress feedback. * * @param AssessmentTestSession $session A given AssessmentTestSession object. * @param array $testMeta An associative array containing meta-data about the test definition taken by the candidate. * @param string $qtiTestDefinitionUri The URI of a reference to an Assessment Test definition in the knowledge base. * @param string $qtiTestCompilationUri The Uri of a reference to an Assessment Test compilation in the knowledge base. * @param string $standalone * @param string $compilationDirs An array containing respectively the private and public compilation directories. * @return array The context of the candidate session. */ public static function buildAssessmentTestContext(AssessmentTestSession $session, array $testMeta, $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone, $compilationDirs) { $context = array(); // The state of the test session. $context['state'] = $session->getState(); // Default values for the test session context. $context['navigationMode'] = null; $context['submissionMode'] = null; $context['remainingAttempts'] = 0; $context['isAdaptive'] = false; $hasBeenPaused = false; if (common_ext_ExtensionsManager::singleton()->isEnabled('taoProctoring')) { $hasBeenPaused = \oat\taoProctoring\helpers\DeliveryHelper::getHasBeenPaused($session->getSessionId()); } $context['hasBeenPaused'] = $hasBeenPaused; if ($session->getState() === AssessmentTestSessionState::INTERACTING) { $config = common_ext_ExtensionsManager::singleton()->getExtensionById('taoQtiTest')->getConfig('testRunner'); // The navigation mode. $context['navigationMode'] = $session->getCurrentNavigationMode(); // The submission mode. $context['submissionMode'] = $session->getCurrentSubmissionMode(); // The number of remaining attempts for the current item. $context['remainingAttempts'] = $session->getCurrentRemainingAttempts(); // Whether or not the current step is time out. $context['isTimeout'] = self::isTimeout($session); // The identifier of the current item. $context['itemIdentifier'] = $session->getCurrentAssessmentItemRef()->getIdentifier(); // The state of the current AssessmentTestSession. $context['itemSessionState'] = $session->getCurrentAssessmentItemSession()->getState(); // Whether the current item is adaptive. $context['isAdaptive'] = $session->isCurrentAssessmentItemAdaptive(); // Whether the current item is the very last one of the test. $context['isLast'] = $session->getRoute()->isLast(); // The current position in the route. $context['itemPosition'] = $session->getRoute()->getPosition(); // Time constraints. $context['timeConstraints'] = self::buildTimeConstraints($session); // Test title. $context['testTitle'] = $session->getAssessmentTest()->getTitle(); // Test Part title. $context['testPartId'] = $session->getCurrentTestPart()->getIdentifier(); // Current Section title. $context['sectionTitle'] = $session->getCurrentAssessmentSection()->getTitle(); // Number of items composing the test session. $context['numberItems'] = $session->getRouteCount(AssessmentTestSession::ROUTECOUNT_FLOW); // Number of items completed during the test session. $context['numberCompleted'] = self::testCompletion($session); // Number of items presented during the test session. $context['numberPresented'] = $session->numberPresented(); // Whether or not the progress of the test can be inferred. $context['considerProgress'] = self::considerProgress($session, $testMeta, $config); // Whether or not the deepest current section is visible. $context['isDeepestSectionVisible'] = $session->getCurrentAssessmentSection()->isVisible(); // The URLs to be called to move forward/backward in the Assessment Test Session or skip or comment. $context['moveForwardUrl'] = self::buildActionCallUrl($session, 'moveForward', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); $context['moveBackwardUrl'] = self::buildActionCallUrl($session, 'moveBackward', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); $context['nextSectionUrl'] = self::buildActionCallUrl($session, 'nextSection', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); $context['skipUrl'] = self::buildActionCallUrl($session, 'skip', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); $context['commentUrl'] = self::buildActionCallUrl($session, 'comment', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); $context['timeoutUrl'] = self::buildActionCallUrl($session, 'timeout', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); $context['endTestSessionUrl'] = self::buildActionCallUrl($session, 'endTestSession', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); $context['keepItemTimedUrl'] = self::buildActionCallUrl($session, 'keepItemTimed', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); // If the candidate is allowed to move backward e.g. first item of the test. $context['canMoveBackward'] = $session->canMoveBackward(); // The places in the test session where the candidate is allowed to jump to. $context['jumps'] = self::buildPossibleJumps($session); // The test review screen setup if (!empty($config['test-taker-review']) && $context['considerProgress']) { // The navigation map in order to build the test navigator $navigator = self::getNavigatorMap($session); if ($navigator !== NavigationMode::LINEAR) { $context['navigatorMap'] = $navigator['map']; $context['itemFlagged'] = self::getItemFlag($session, $context['itemPosition']); } else { $navigator = self::countItems($session); } // Extract the progression stats $context['numberFlagged'] = $navigator['numberItemsFlagged']; $context['numberItemsPart'] = $navigator['numberItemsPart']; $context['numberItemsSection'] = $navigator['numberItemsSection']; $context['numberCompletedPart'] = $navigator['numberCompletedPart']; $context['numberCompletedSection'] = $navigator['numberCompletedSection']; $context['numberPresentedPart'] = $navigator['numberPresentedPart']; $context['numberPresentedSection'] = $navigator['numberPresentedSection']; $context['numberFlaggedPart'] = $navigator['numberFlaggedPart']; $context['numberFlaggedSection'] = $navigator['numberFlaggedSection']; $context['itemPositionPart'] = $navigator['itemPositionPart']; $context['itemPositionSection'] = $navigator['itemPositionSection']; // The URLs to be called to move to a particular item in the Assessment Test Session or mark item for later review. $context['jumpUrl'] = self::buildActionCallUrl($session, 'jumpTo', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); $context['markForReviewUrl'] = self::buildActionCallUrl($session, 'markForReview', $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone); } else { // Setup data for progress bar when displaying position and timed section exit control $numberItems = self::countItems($session); $context['numberCompletedPart'] = $numberItems['numberCompletedPart']; $context['numberCompletedSection'] = $numberItems['numberCompletedSection']; $context['numberItemsSection'] = $numberItems['numberItemsSection']; $context['numberItemsPart'] = $numberItems['numberItemsPart']; $context['itemPositionPart'] = $numberItems['itemPositionPart']; $context['itemPositionSection'] = $numberItems['itemPositionSection']; } // The code to be executed to build the ServiceApi object to be injected in the QTI Item frame. $context['itemServiceApiCall'] = self::buildServiceApi($session, $qtiTestDefinitionUri, $qtiTestCompilationUri); // Rubric Blocks. $rubrics = array(); // -- 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 ($session->getRoute()->current()->getRubricBlockRefs() as $rubric) { $data = $compilationDirs['private']->read($rubric->getHref()); $tmpDir = \tao_helpers_File::createTempDir(); $tmpFile = $tmpDir . basename($rubric->getHref()); file_put_contents($tmpFile, $data); ob_start(); include $tmpFile; $rubrics[] = ob_get_clean(); unlink($tmpFile); rmdir($tmpDir); } $context['rubrics'] = $rubrics; // Comment allowed? Skipping allowed? Logout or Exit allowed ? $context['allowComment'] = self::doesAllowComment($session); $context['allowSkipping'] = self::doesAllowSkipping($session); $context['exitButton'] = self::doesAllowExit($session); $context['logoutButton'] = self::doesAllowLogout($session); $context['categories'] = self::getCategories($session); // loads the specific config into the context object $configMap = array('timerWarning' => 'timerWarning', 'progress-indicator' => 'progressIndicator', 'progress-indicator-scope' => 'progressIndicatorScope', 'test-taker-review' => 'reviewScreen', 'test-taker-review-region' => 'reviewRegion', 'test-taker-review-scope' => 'reviewScope', 'test-taker-review-prevents-unseen' => 'reviewPreventsUnseen', 'test-taker-review-can-collapse' => 'reviewCanCollapse', 'next-section' => 'nextSection', 'keep-timer-up-to-timeout' => 'keepTimerUpToTimeout'); foreach ($configMap as $configKey => $contextKey) { if (isset($config[$configKey])) { $context[$contextKey] = $config[$configKey]; } } // optionally extend the context if (isset($config['extraContextBuilder']) && class_exists($config['extraContextBuilder'])) { $builder = new $config['extraContextBuilder'](); if ($builder instanceof \oat\taoQtiTest\models\TestContextBuilder) { $builder->extendAssessmentTestContext($context, $session, $testMeta, $qtiTestDefinitionUri, $qtiTestCompilationUri, $standalone, $compilationDirs); } else { common_Logger::i('Try to use an extra context builder class that is not an instance of \\oat\\taoQtiTest\\models\\TestContextBuilder!'); } } } return $context; }
/** * Copy csv data into tmp file with updated line referenced by $id * Copy tmp file to csv && remove tmp file * @param $id * @param $entityData * @return bool|string|void * @throws StorageException */ private function update($id, $entityData = []) { $tmpFile = \tao_helpers_File::createTempDir() . 'store.csv'; $tmpHandle = fopen($tmpFile, 'w'); $line = 1; $index = 0; while (($data = fgetcsv($this->handle, 1000, ";")) !== false) { if ($line === 1) { $keys = $data; if (($index = array_search('id', $keys, true)) === false) { return false; } } if ($data[$index] == $id) { foreach ($data as $index => $value) { if (empty($entityData[$keys[$index]])) { $entityData[$keys[$index]] = $value; } } } else { fputcsv($tmpHandle, $data, ';'); } $line++; } $entityData = array_merge(array_flip($keys), $entityData); fputcsv($tmpHandle, $entityData, ';'); fclose($tmpHandle); fclose($this->handle); \tao_helpers_File::copy($tmpFile, $this->getOption('filename')) && unlink($tmpFile); return; }
/** * Copy all remote resource (absolute URLs to another host) contained in a rubricBlock into a dedicated directory. Remote resources * can be refereced by the following QTI classes/attributes: * * * a:href * * object:data * * img:src * * @param AssessmentTest $assessmentTest An AssessmentTest object. * @throws taoQtiTest_models_classes_QtiTestCompilationFailedException If a remote resource cannot be retrieved. */ protected function copyRemoteResources(RubricBlock $rubricBlock) { $ds = DIRECTORY_SEPARATOR; $tmpDir = tao_helpers_File::createTempDir(); $destPath = trim($this->getExtraPath(), $ds) . $ds . TAOQTITEST_REMOTE_FOLDER . $ds; // Search for all class-attributes in QTI-XML that might reference a remote file. $search = $rubricBlock->getComponentsByClassName(array('a', 'object', 'img')); foreach ($search as $component) { switch ($component->getQtiClassName()) { case 'object': $url = $component->getData(); break; case 'img': $url = $component->getSrc(); break; } if (isset($url) && !preg_match('@^' . ROOT_URL . '@', $url) && !Url::isRelative($url)) { $tmpFile = taoItems_helpers_Deployment::retrieveFile($url, $tmpDir); if ($tmpFile !== false) { $pathinfo = pathinfo($tmpFile); $handle = fopen($tmpFile, 'r'); $this->getPublicDirectory()->writeStream($destPath . $pathinfo['basename'], $handle); fclose($handle); unlink($tmpFile); $newUrl = TAOQTITEST_REMOTE_FOLDER . '/' . $pathinfo['basename']; switch ($component->getQtiClassName()) { case 'object': $component->setData($newUrl); break; case 'img': $component->setSrc($newUrl); break; } } else { $msg = "The remote resource referenced by '{$url}' could not be retrieved."; throw new taoQtiTest_models_classes_QtiTestCompilationFailedException($msg, $this->getResource(), taoQtiTest_models_classes_QtiTestCompilationFailedException::REMOTE_RESOURCE); } } } }
/** * Copy file content to temp file. Path is return to be downloaded * * @see \oat\tao\model\media\MediaBrowser::download * @param string $link * @return string * @throws \common_Exception * @throws \tao_models_classes_FileNotFoundException * @throws common_exception_Error */ public function download($link) { $file = $this->getFile($link); $relPath = $this->getItemDirectory()->getRelPath($file); $tmpDir = rtrim(\tao_helpers_File::createTempDir(), '/'); $tmpFile = $tmpDir . $relPath; if (!is_dir(dirname($tmpFile))) { mkdir(dirname($tmpFile), 0755, true); } if (($resource = fopen($tmpFile, 'w')) !== false) { stream_copy_to_stream($file->readStream(), $resource); fclose($resource); return $tmpFile; } throw new \common_Exception('Unable to write "' . $link . '" into tmp folder("' . $tmpFile . '").'); }
/** * tests initialization */ public function setUp() { $this->privateDir = \tao_helpers_File::createTempDir(); $this->adapterFixture = 'adapterFixture'; }
public function deleteData() { if (($handle = fopen($this->filePath, "r")) !== FALSE) { $tmpFile = \tao_helpers_File::createTempDir() . 'store.csv'; $tmpHandle = fopen($tmpFile, 'w'); $line = 1; $index = 0; while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { if ($line === 1) { $keys = $data; if (($index = array_search('key', $keys, true)) === false) { return false; } } if ($data[$index] !== $this->key) { fputcsv($tmpHandle, $data, ';'); } $line++; } fclose($tmpHandle); fclose($handle); return \tao_helpers_File::copy($tmpFile, $this->filePath) && unlink($tmpFile); } return false; }
/** * Unzip archive from the upload form * * @param $archiveFile * @return string temporary directory zipfile was extracted to */ protected function extractArchive($archiveFile) { $archiveDir = \tao_helpers_File::createTempDir(); $archiveObj = new \ZipArchive(); $archiveHandle = $archiveObj->open($archiveFile); if (true !== $archiveHandle) { throw new \common_Exception('Unable to open archive ' . $archiveFile); } if (!$archiveObj->extractTo($archiveDir)) { $archiveObj->close(); throw new \common_Exception('Unable to extract to ' . $archiveDir); } $archiveObj->close(); return $archiveDir; }
public function testImportRules() { $path = $this->getSamplePath('/csv/users1-header-rules-validator.csv'); $file = tao_helpers_File::createTempDir() . '/temp-import-rules-validator.csv'; tao_helpers_File::copy($path, $file); $this->assertFileExists($file); $importer = new CsvBasicImporter(); $class = $this->prophesize('\\core_kernel_classes_Class'); $resource = $this->prophesize('\\core_kernel_classes_Resource'); $class->createInstanceWithProperties(["label" => ["Correct row"], "firstName" => ["Jérôme"], "lastName" => ["Bogaerts"], "login" => ["jbogaerts"], "mail" => ["*****@*****.**"], "password" => ["jbogaerts!!!111Ok"], "UserUIlg" => ["http://www.tao.lu/Ontologies/TAO.rdf#LangEN"]])->shouldBeCalledTimes(1)->willReturn($resource->reveal()); $importer->setValidators(['label' => [tao_helpers_form_FormFactory::getValidator('Length', ["max" => 20])], 'firstName' => [tao_helpers_form_FormFactory::getValidator('NotEmpty'), tao_helpers_form_FormFactory::getValidator('Length', ["min" => 2, "max" => 25])], 'lastName' => [tao_helpers_form_FormFactory::getValidator('NotEmpty'), tao_helpers_form_FormFactory::getValidator('Length', ["min" => 2, "max" => 12])], 'login' => [tao_helpers_form_FormFactory::getValidator('NotEmpty'), tao_helpers_form_FormFactory::getValidator('AlphaNum'), tao_helpers_form_FormFactory::getValidator('Unique'), tao_helpers_form_FormFactory::getValidator('Length', ["min" => 2, "max" => 12])], 'mail' => [tao_helpers_form_FormFactory::getValidator('NotEmpty'), tao_helpers_form_FormFactory::getValidator('Email'), tao_helpers_form_FormFactory::getValidator('Length', ["min" => 6, "max" => 100])], 'password' => [tao_helpers_form_FormFactory::getValidator('NotEmpty')], 'UserUIlg' => [tao_helpers_form_FormFactory::getValidator('Url')]]); $report = $importer->import($class->reveal(), ['file' => $file, 'map' => ['label' => "0", 'firstName' => "1", 'lastName' => "2", 'login' => "3", 'mail' => "4", 'password' => "5", 'UserUIlg' => "6"]]); $this->assertInstanceOf('common_report_Report', $report); $this->assertEquals(common_report_Report::TYPE_WARNING, $report->getType()); $this->assertCount(6, $report->getErrors()); //cause import has errors $this->assertFileExists($file); tao_helpers_File::remove($file); $this->assertFileNotExists($file); }
/** * @param $cssArray array that contains selectors, property and value * ['.myselector1' => ['property1'=>'value', 'property2'=>'value2']] * @param $filename string the name of the css file */ public function generateCss($cssArray, $filename) { $tmpDir = \tao_helpers_File::createTempDir(); $css = "/* === These styles are generated, do not edit! === */ \n"; $css .= CssHandler::arrayToCss($cssArray, false); $css .= "\n/* === Add your own styles below this line === */\n"; $tmpFile = $tmpDir . '/theme.css'; file_put_contents($tmpFile, $css); $this->storeFile($tmpFile, $filename); }
public function testIsIdentical() { $testfolder = tao_helpers_File::createTempDir(); $this->assertTrue(is_dir($testfolder)); $zip = new ZipArchive(); $this->assertTrue($zip->open(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'samples' . DIRECTORY_SEPARATOR . 'fileHelper.zip')); $this->assertTrue($zip->extractTo($testfolder)); $zip->close(); $reference = $testfolder . 'reference'; $this->assertTrue(is_dir($reference)); $testContent = $testfolder . DIRECTORY_SEPARATOR . 'testContent'; $testEmptyDir = $testfolder . DIRECTORY_SEPARATOR . 'testEmptyDir'; $testIdent = $testfolder . DIRECTORY_SEPARATOR . 'testIdent'; $testMissingDir = $testfolder . DIRECTORY_SEPARATOR . 'testMissingDir'; $testRenamedFile = $testfolder . DIRECTORY_SEPARATOR . 'testRenamedFile'; $testRenamedEmptyDir = $testfolder . DIRECTORY_SEPARATOR . 'testRenamedEmptyDir'; $this->assertTrue(tao_helpers_File::isIdentical($reference, $reference)); $this->assertTrue(tao_helpers_File::isIdentical($reference, $testIdent)); $this->assertFalse(tao_helpers_File::isIdentical($reference, $testContent)); $this->assertFalse(tao_helpers_File::isIdentical($reference, $testEmptyDir)); $this->assertFalse(tao_helpers_File::isIdentical($reference, $testMissingDir)); $this->assertFalse(tao_helpers_File::isIdentical($reference, $testRenamedFile)); $this->assertFalse(tao_helpers_File::isIdentical($reference, $testRenamedEmptyDir)); $this->assertTrue(tao_helpers_File::delTree($testfolder)); $this->assertFalse(is_dir($testfolder)); }