/**
  * (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;
 }
 /**
  * Import file entry point by using $this->service
  * Check POST method & get valid uploaded file
  */
 public function import()
 {
     $fileUploadName = "qtiPackage";
     if ($this->getRequestMethod() != Request::HTTP_POST) {
         throw new \common_exception_NotImplemented('Only post method is accepted to import Qti package.');
     }
     if (tao_helpers_Http::hasUploadedFile($fileUploadName)) {
         $file = tao_helpers_Http::getUploadedFile($fileUploadName);
         $mimeType = tao_helpers_File::getMimeType($file['tmp_name']);
         if (!in_array($mimeType, self::$accepted_types)) {
             $this->returnFailure(new common_exception_BadRequest());
         } else {
             $report = $this->service->importQtiTest($file['tmp_name']);
             if ($report->getType() === common_report_Report::TYPE_SUCCESS) {
                 $data = array();
                 foreach ($report as $r) {
                     $values = $r->getData();
                     $testid = $values->rdfsResource->getUri();
                     foreach ($values->items as $item) {
                         $itemsid[] = $item->getUri();
                     }
                     $data[] = array('testId' => $testid, 'testItems' => $itemsid);
                 }
                 return $this->returnSuccess($data);
             } else {
                 return $this->returnFailure(new common_exception_InconsistentData($report->getMessage()));
             }
         }
     } else {
         return $this->returnFailure(new common_exception_BadRequest());
     }
 }
Esempio n. 3
0
 public static function outputFile($relPath, $filename = null)
 {
     $fullpath = self::getExportPath() . DIRECTORY_SEPARATOR . $relPath;
     if (tao_helpers_File::securityCheck($fullpath, true) && file_exists($fullpath)) {
         Context::getInstance()->getResponse()->setContentHeader(tao_helpers_File::getMimeType($fullpath));
         $fileName = empty($filename) ? basename($fullpath) : $filename;
         header('Content-Disposition: attachment; fileName="' . $fileName . '"');
         header("Content-Length: " . filesize($fullpath));
         //Clean all levels of output buffering
         while (ob_get_level() > 0) {
             ob_end_clean();
         }
         flush();
         $fp = fopen($fullpath, "r");
         if ($fp !== false) {
             while (!feof($fp)) {
                 echo fread($fp, 65536);
                 flush();
             }
             fclose($fp);
             @unlink($fullpath);
         } else {
             common_Logger::e('Unable to open File to export' . $fullpath);
         }
     } else {
         common_Logger::e('Could not find File to export: ' . $fullpath);
     }
 }
 /**
  * (non-PHPdoc)
  * @see tao_models_classes_import_ImportHandler::import()
  */
 public function import($class, $form)
 {
     $fileInfo = $form->getValue('source');
     //import for CSV
     if (isset($fileInfo)) {
         set_time_limit(200);
         //the zip extraction is a long process that can exced the 30s timeout
         //get the services instances we will need
         $itemService = taoItems_models_classes_ItemsService::singleton();
         $uploadedFile = $fileInfo['uploaded_file'];
         $uploadedFileBaseName = basename($uploadedFile);
         // uploaded file name contains an extra prefix that we have to remove.
         $uploadedFileBaseName = preg_replace('/^([0-9a-z])+_/', '', $uploadedFileBaseName, 1);
         $uploadedFileBaseName = preg_replace('/.zip|.ZIP$/', '', $uploadedFileBaseName);
         $validate = count($form->getValue('disable_validation')) == 0 ? true : false;
         try {
             $report = taoDelivery_models_classes_import_Assembler::importDelivery($class, $uploadedFile);
         } catch (common_Exception $e) {
             $report = common_report_Report::createFailure(__('An error occured during the import'));
             if ($e instanceof common_exception_UserReadableException) {
                 $report->add($e);
             }
         }
         tao_helpers_File::remove($uploadedFile);
     } else {
         throw new common_exception_Error('No file provided as parameter \'source\' for OWI import');
     }
     return $report;
 }
 /**
  * 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;
 }
 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);
 }
 /**
  * get the link and return the file that match it
  * @param string $link the link provided by storeFile
  * @return string $filename the file that match the link
  * @throws \common_exception_Error
  */
 public function retrieveFile($link)
 {
     if (!\tao_helpers_File::securityCheck($link)) {
         throw new \common_exception_Error('Unsecure file link found');
     }
     return $this->getBaseDir() . $link;
 }
 /**
  * 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;
 }
Esempio n. 9
0
 /**
  * (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;
 }
 /**
  * (non-PHPdoc)
  * @see tao_models_classes_import_ImportHandler::import()
  */
 public function import($class, $form)
 {
     $fileInfo = $form->getValue('source');
     //import for CSV
     if (isset($fileInfo)) {
         \helpers_TimeOutHelper::setTimeOutLimit(\helpers_TimeOutHelper::MEDIUM);
         //get the services instances we will need
         $itemService = \taoItems_models_classes_ItemsService::singleton();
         $uploadedFile = $fileInfo['uploaded_file'];
         $uploadedFileBaseName = basename($uploadedFile);
         // uploaded file name contains an extra prefix that we have to remove.
         $uploadedFileBaseName = preg_replace('/^([0-9a-z])+_/', '', $uploadedFileBaseName, 1);
         $uploadedFileBaseName = preg_replace('/.zip|.ZIP$/', '', $uploadedFileBaseName);
         $validate = count($form->getValue('disable_validation')) == 0 ? true : false;
         try {
             $importer = new Assembler();
             $report = $importer->importDelivery($class, $uploadedFile);
         } catch (\common_Exception $e) {
             $report = common_report_Report::createFailure(__('An error occured during the import'));
             if ($e instanceof \common_exception_UserReadableException) {
                 $report->add($e);
             }
         }
         \tao_helpers_File::remove($uploadedFile);
         \helpers_TimeOutHelper::reset();
     } else {
         throw new \common_exception_Error('No file provided as parameter \'source\' for Delivery Assembly import');
     }
     return $report;
 }
Esempio n. 11
0
 public function getAsset()
 {
     $item = new \core_kernel_classes_Resource($this->getRequestParameter('id'));
     $assetPath = $this->getRequestParameter('asset');
     $mimeType = \tao_helpers_File::getMimeType($assetPath, true);
     header('Content-Type: ' . $mimeType);
     $loader = new Loader($item);
     $content = $loader->getAssetContent($assetPath);
     echo $content;
 }
 public static function buildFile(core_kernel_classes_Resource $test, $lang, $relPath, $filters = array())
 {
     $file = null;
     $baseDir = self::getBaseDir($test);
     $path = $baseDir . ltrim($relPath, '/');
     $mime = tao_helpers_File::getMimeType($path);
     if (count($filters) == 0 || in_array($mime, $filters)) {
         $file = array('name' => basename($path), 'mime' => $mime, 'size' => filesize($path), 'url' => _url('download', 'TestContent', 'taoQtiTest', array('uri' => $test->getUri(), 'lang' => $lang, 'path' => $relPath)));
     }
     return $file;
 }
Esempio n. 13
0
 /**
  * Get file path to save message
  * @param User $receiver
  * @param boolean $refresh whether the file path must be regenerated.
  */
 public function getFilePath(User $receiver)
 {
     $basePath = $this->getOption(self::CONFIG_FILEPATH);
     if (is_null($basePath) || !file_exists($basePath)) {
         throw new \common_exception_InconsistentData('Missing path ' . self::CONFIG_FILEPATH . ' for ' . __CLASS__);
     }
     $path = $basePath . \tao_helpers_File::getSafeFileName($receiver->getIdentifier()) . DIRECTORY_SEPARATOR;
     if (!file_exists($path)) {
         mkdir($path);
     }
     return $path . \tao_helpers_File::getSafeFileName('message.html', $path);
 }
Esempio n. 14
0
 public function send(Message $message)
 {
     $receiver = $message->getTo();
     $path = $this->getOption(self::CONFIG_FILEPATH) . \tao_helpers_File::getSafeFileName($receiver->getIdentifier()) . DIRECTORY_SEPARATOR;
     if (!file_exists($path)) {
         mkdir($path);
     }
     $messageFile = $path . \tao_helpers_File::getSafeFileName('message.html', $path);
     \common_Logger::d($messageFile);
     $written = file_put_contents($messageFile, $message->getBody());
     return $written !== false;
 }
 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 run()
 {
     $ext = common_ext_ExtensionsManager::singleton()->getExtensionById('ltiProvider');
     if ($ext->isInstalled()) {
         common_Logger::t('Uninstall ltiProvider');
         $db = core_kernel_classes_DbWrapper::singleton();
         $sql = "DELETE from extensions where id ='ltiProvider';";
         $db->exec($sql);
         tao_helpers_File::delTree($ext->getConstant('BASE_PATH'));
         $newExt = common_ext_ExtensionsManager::singleton()->getExtensionById('taoLti');
         taoUpdate_models_classes_DataMigrationService::singleton()->installExtension($newExt);
     }
 }
Esempio n. 17
0
 private static function migrateFrom09To091()
 {
     // Get all items...
     $itemService = \taoItems_models_classes_ItemsService::singleton();
     $itemClass = $itemService->getRootClass();
     foreach ($itemClass->getInstances(true) as $item) {
         if ($itemService->hasItemModel($item, array(TAO_ITEM_MODEL_QTI))) {
             $path = $itemService->getDefaultItemFolder($item);
             $qtiXml = $itemService->getItemContent($item);
             if (empty($qtiXml) === false) {
                 $qtiDom = new \DOMDocument('1.0', 'UTF-8');
                 $qtiDom->loadXML($qtiXml);
                 // Get all stylesheet hrefs.
                 $hrefs = Utils::getStylesheetHrefs($qtiDom);
                 // Make sure the hrefs are refering existing files.
                 for ($i = 0; $i < count($hrefs); $i++) {
                     $href = $hrefs[$i];
                     if (is_readable($path . $href) === false) {
                         \common_Logger::i("The stylesheet->href '{$path}.{$href}' does not reference an existing file. Trying to repair...");
                         // Let's try with another name...
                         $pathinfo = pathinfo($href);
                         $altFileName = \tao_helpers_File::getSafeFileName($pathinfo['basename']);
                         $dirSep = $pathinfo['dirname'] !== '.' ? $pathInfo['dirname'] . DIRECTORY_SEPARATOR : '';
                         $altPath = $path . $dirSep . $altFileName;
                         if (is_readable($altPath)) {
                             // Bingo! We rebind.
                             $hrefs[$i] = $dirSep . $altFileName;
                             \common_Logger::i("Repaired with new href '{$dirSep}.{$altFileName}}'.");
                         } else {
                             // It's definitely broken...
                             unset($hrefs[$i]);
                             \common_Logger::i("Could not be repaired! QTI stylesheet component removed from item.");
                         }
                     }
                 }
                 // Reput them in the item with cleanup enabled
                 // to solve the XMLSchema validation issue.
                 if (count($hrefs) > 0) {
                     $href = array_shift($hrefs);
                     Utils::appendStylesheet($qtiDom, $href, true);
                 }
                 // Append the rest of the stylesheets.
                 foreach ($hrefs as $href) {
                     Utils::appendStylesheet($qtiDom, $href);
                 }
                 $itemService->setItemContent($item, $qtiDom->saveXML());
             }
         }
     }
 }
 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());
 }
 /**
  *
  * @param unknown $params
  */
 public function __invoke($params)
 {
     if (count($params) != 2) {
         return new \common_report_Report(\common_report_Report::TYPE_ERROR, __('Usage: %s DELIVERY_URI OUTPUT_FILE', __CLASS__));
     }
     $deliveryUri = array_shift($params);
     $delivery = new \core_kernel_classes_Resource($deliveryUri);
     if (!$delivery->exists()) {
         return new \common_report_Report(\common_report_Report::TYPE_ERROR, __('Delivery \'%s\' not found', $deliveryUri));
     }
     $file = array_shift($params);
     \common_ext_ExtensionsManager::singleton()->getExtensionById('taoDeliveryRdf');
     $tmpFile = Assembler::exportCompiledDelivery($delivery);
     \tao_helpers_File::move($tmpFile, $file);
     return new \common_report_Report(\common_report_Report::TYPE_SUCCESS, __('Exported %1$s to %2$s', $delivery->getLabel(), $file));
 }
 protected static function deleteDependencies(\core_kernel_classes_Triple $triple)
 {
     if ($triple->predicate == 'http://www.tao.lu/Ontologies/TAOItem.rdf#ItemContent') {
         $file = new \core_kernel_versioning_File($triple->object);
         if ($file->exists()) {
             $sourceDir = dirname($file->getAbsolutePath());
             $file->delete();
             \tao_helpers_File::delTree($sourceDir);
         }
     } elseif (CloneHelper::isFileReference($triple)) {
         $file = new \core_kernel_versioning_File($triple->object);
         if ($file->exists()) {
             $file->delete();
         }
     }
 }
 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;
 }
Esempio n. 23
0
 /**
  * (non-PHPdoc)
  * @see tao_models_classes_export_ExportHandler::export()
  */
 public function export($formValues, $destination)
 {
     $file = null;
     if (isset($formValues['filename']) && isset($formValues['resource'])) {
         $class = new core_kernel_classes_Class($formValues['resource']);
         common_Logger::i('Exporting ' . $class->getUri());
         $adapter = new tao_helpers_data_GenerisAdapterRdf();
         $rdf = $adapter->export($class);
         if (!empty($rdf)) {
             $name = $formValues['filename'] . '_' . time() . '.rdf';
             $path = tao_helpers_File::concat(array($destination, $name));
             if (file_put_contents($path, $rdf)) {
                 $file = $path;
             }
         }
     }
     return $file;
 }
 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);
 }
 /**
  * (non-PHPdoc)
  * @see tao_models_classes_import_ImportHandler::import()
  */
 public function import($class, $form)
 {
     try {
         $fileInfo = $form->getValue('source');
         if (isset($fileInfo['uploaded_file'])) {
             $uploadedFile = $fileInfo['uploaded_file'];
             // The zip extraction is a long process that can exceed the 30s timeout
             helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::LONG);
             $report = taoQtiTest_models_classes_QtiTestService::singleton()->importMultipleTests($class, $uploadedFile);
             helpers_TimeOutHelper::reset();
             tao_helpers_File::remove($uploadedFile);
         } else {
             throw new common_exception_Error('No source file for import');
         }
         return $report;
     } catch (Exception $e) {
         return common_report_Report::createFailure($e->getMessage());
     }
 }
 /**
  * Create a media instance from a file, and define its class and language
  *
  * @param string $fileSource path to the file to create instance from
  * @param string $classUri parent to add the instance to
  * @param string $language language of the content
  * @param string $label label of the instance
  * @param string $mimeType mimeType of the file
  * @return string | bool $instanceUri or false on error
  */
 public function createMediaInstance($fileSource, $classUri, $language, $label = null, $mimeType = null)
 {
     $clazz = new \core_kernel_classes_Class($classUri);
     //get the file MD5
     $md5 = md5_file($fileSource);
     //create media instance
     $label = is_null($label) ? basename($fileSource) : $label;
     $fileManager = FileManager::getFileManagementModel();
     $link = $fileManager->storeFile($fileSource, $label);
     if ($link !== false) {
         $mimeType = is_null($mimeType) ? \tao_helpers_File::getMimeType($fileSource) : $mimeType;
         $instance = $clazz->createInstanceWithProperties(array(RDFS_LABEL => $label, MEDIA_LINK => $link, MEDIA_LANGUAGE => $language, MEDIA_MD5 => $md5, MEDIA_MIME_TYPE => $mimeType, MEDIA_ALT_TEXT => $label));
         if (common_ext_ExtensionsManager::singleton()->isEnabled('taoRevision')) {
             \common_Logger::i('Auto generating initial revision');
             RevisionService::commit($instance, __('Initial import'));
         }
         return $instance->getUri();
     }
     return false;
 }
Esempio n. 27
0
 /**
  * Short description of method evaluate
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param  values
  * @return boolean
  */
 public function evaluate($values)
 {
     $returnValue = (bool) false;
     $mimetype = '';
     if (is_array($values)) {
         if (file_exists($values['uploaded_file'])) {
             $mimetype = tao_helpers_File::getMimeType($values['uploaded_file']);
             common_Logger::i($mimetype);
         }
         if (!empty($mimetype)) {
             if (in_array($mimetype, $this->options['mimetype'])) {
                 $returnValue = true;
             } else {
                 $this->message .= " " . implode(', ', $this->options['mimetype']) . " are expected but {$mimetype} detected";
             }
         } else {
             common_Logger::i('mimetype empty');
         }
     }
     return (bool) $returnValue;
 }
Esempio n. 28
0
 /**
  * Short description of method evaluate
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param  values
  * @return boolean
  */
 public function evaluate($values)
 {
     $returnValue = (bool) false;
     $mimetype = '';
     if (is_array($values)) {
         if (file_exists($values['uploaded_file'])) {
             $mimetype = tao_helpers_File::getMimeType($values['uploaded_file']);
             common_Logger::d($mimetype);
         }
         if (!empty($mimetype)) {
             if (in_array($mimetype, $this->getOption('mimetype'))) {
                 $returnValue = true;
             } else {
                 $this->setMessage(__('%1$s expected but %2$s detected', implode(', ', $this->getOption('mimetype')), $mimetype));
             }
         } else {
             common_Logger::i('mimetype empty');
         }
     }
     return (bool) $returnValue;
 }
 /**
  * (non-PHPdoc)
  * @see \oat\oatbox\action\Action::__invoke()
  */
 public function __invoke($params)
 {
     \common_ext_ExtensionsManager::singleton()->getExtensionById('taoDeliveryRdf');
     if (count($params) != 2) {
         return new \common_report_Report(\common_report_Report::TYPE_ERROR, __('Usage: %s DELIVERY_CLASS_URI OUTPUT_DIRECTORY', __CLASS__));
     }
     $deliveryClassUri = array_shift($params);
     $deliveryClass = new \core_kernel_classes_Class($deliveryClassUri);
     $dir = array_shift($params);
     if (!file_exists($dir) && !mkdir($dir)) {
         return new \common_report_Report(\common_report_Report::TYPE_ERROR, __('Directory %s doesn\'t exist', $dir));
     }
     $dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
     $report = new \common_report_Report(\common_report_Report::TYPE_SUCCESS, __('Exporting %s', $deliveryClass->getLabel()));
     foreach ($deliveryClass->getInstances(true) as $delivery) {
         $destFile = $dir . \tao_helpers_File::getSafeFileName($delivery->getLabel()) . '.zip';
         $tmpFile = Assembler::exportCompiledDelivery($delivery);
         \tao_helpers_File::move($tmpFile, $destFile);
         $report->add(new \common_report_Report(\common_report_Report::TYPE_SUCCESS, __('Exported %1$s to %2$s', $delivery->getLabel(), $destFile)));
     }
     return $report;
 }
 /**
  * (non-PHPdoc)
  * @see tao_models_classes_export_ExportHandler::export()
  */
 public function export($formValues, $destination)
 {
     $report = common_report_Report::createSuccess();
     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 = $this->createManifest();
             foreach ($instances as $instance) {
                 $testResource = new core_kernel_classes_Resource($instance);
                 $testExporter = $this->createExporter($testResource, $zip, $manifest);
                 common_Logger::d('Export ' . $instance);
                 $subReport = $testExporter->export();
                 if ($report->getType() !== common_report_Report::TYPE_ERROR && ($subReport->containsError() || $subReport->getType() === common_report_Report::TYPE_ERROR)) {
                     $report->setType(common_report_Report::TYPE_ERROR);
                     $report->setMessage(__('Not all test could be export', $testResource->getLabel()));
                 }
                 $report->add($subReport);
             }
             $report->setData($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 $report;
 }