/**
  * Copy the resources from one directory to another
  * 
  * @param string $sourceDirectory
  * @param string $destinationDirectory
  * @param array $excludeFiles
  * @return boolean
  */
 public static function copyResources($sourceDirectory, $destinationDirectory, $excludeFiles = array())
 {
     //copy the resources
     $exclude = array_merge($excludeFiles, array('.', '..', '.svn'));
     $success = true;
     foreach (scandir($sourceDirectory) as $file) {
         if (!in_array($file, $exclude)) {
             $success &= tao_helpers_File::copy($sourceDirectory . $file, $destinationDirectory . $file, true);
         }
     }
     return $success;
 }
 /**
  * (non-PHPdoc)
  * @see taoTests_models_classes_TestModel::cloneContent()
  */
 public function cloneContent(core_kernel_classes_Resource $source, core_kernel_classes_Resource $destination)
 {
     $propInstanceContent = new core_kernel_classes_Property(TEST_TESTCONTENT_PROP);
     //get the source DirectoryId
     $sourceDirectoryId = $source->getOnePropertyValue($propInstanceContent);
     if (is_null($sourceDirectoryId)) {
         throw new \common_exception_FileSystemError(__('Unknown test directory'));
     }
     //get the real directory (or the encoded items if an old test)
     $directory = \tao_models_classes_service_FileStorage::singleton()->getDirectoryById($sourceDirectoryId->literal);
     //an old test so create the content.json to copy
     if (!is_dir($directory->getPath())) {
         $directory = \tao_models_classes_service_FileStorage::singleton()->spawnDirectory(true);
         $file = $directory->getPath() . 'content.json';
         file_put_contents($file, json_encode($sourceDirectoryId));
     }
     $destDirectoryId = $destination->getOnePropertyValue($propInstanceContent);
     if (is_null($destDirectoryId)) {
         //create the destination directory
         $destDirectory = \tao_models_classes_service_FileStorage::singleton()->spawnDirectory(true);
     } else {
         //get the real directory (or the encoded items if an old test)
         $destDirectory = \tao_models_classes_service_FileStorage::singleton()->getDirectoryById($destDirectoryId->literal);
         //an old test so create the directory
         if (!is_dir($destDirectory->getPath())) {
             $destDirectory = \tao_models_classes_service_FileStorage::singleton()->spawnDirectory(true);
         }
     }
     \tao_helpers_File::copy($directory->getPath(), $destDirectory->getPath(), true);
     $destination->editPropertyValues($propInstanceContent, $destDirectory->getId());
 }
 /**
  * Validate an xml file, convert file linked inside and store it into media manager
  * @param \core_kernel_classes_Resource $instance the instance to edit
  * @param string $lang language of the shared stimulus
  * @param string $xmlFile File to store
  * @return \common_report_Report
  */
 protected function replaceSharedStimulus($instance, $lang, $xmlFile)
 {
     //if the class does not belong to media classes create a new one with its name (for items)
     $mediaClass = new core_kernel_classes_Class(MediaService::ROOT_CLASS_URI);
     if (!$instance->isInstanceOf($mediaClass)) {
         $report = \common_report_Report::createFailure('The instance ' . $instance->getUri() . ' is not a Media instance');
         return $report;
     }
     SharedStimulusImporter::isValidSharedStimulus($xmlFile);
     $name = basename($xmlFile, '.xml');
     $name .= '.xhtml';
     $filepath = dirname($xmlFile) . '/' . $name;
     \tao_helpers_File::copy($xmlFile, $filepath);
     $service = MediaService::singleton();
     if (!$service->editMediaInstance($filepath, $instance->getUri(), $lang)) {
         $report = \common_report_Report::createFailure(__('Fail to edit Shared Stimulus'));
     } else {
         $report = \common_report_Report::createSuccess(__('Shared Stimulus edited successfully'));
     }
     return $report;
 }
 /**
  * Store a file referenced by $qtiResource into the final $testContent folder. If the path provided
  * by $qtiResource contains sub-directories, they will be created before copying the file (even
  * if $copy = false).
  * 
  * @param core_kernel_file_File|string $testContent The pointer to the TAO Test Content folder.
  * @param oat\taoQtiItem\model\qti\Resource|string $qtiTestResource The QTI resource to be copied into $testContent. If given as a string, it must be the relative (to the IMS QTI Package) path to the resource file.
  * @param string $origin The path to the directory (root folder of extracted IMS QTI package) containing the QTI resource to be copied.
  * @param boolean $copy If set to false, the file will not be actually copied.
  * @param string $rename A new filename  e.g. 'file.css' to be used at storage time.
  * @return string The path were the file was copied/has to be copied (depending on the $copy argument).
  * @throws InvalidArgumentException If one of the above arguments is invalid.
  * @throws common_Exception If the copy fails.
  */
 public static function storeQtiResource($testContent, $qtiResource, $origin, $copy = true, $rename = '')
 {
     if ($testContent instanceof core_kernel_file_File) {
         $contentPath = $testContent->getAbsolutePath();
     } else {
         if (is_string($testContent) === true) {
             $contentPath = $testContent;
         } else {
             throw new InvalidArgumentException("The 'testContent' argument must be a string or a taoQTI_models_classes_QTI_Resource object.");
         }
     }
     $ds = DIRECTORY_SEPARATOR;
     $contentPath = rtrim($contentPath, $ds);
     if ($qtiResource instanceof Resource) {
         $filePath = $qtiResource->getFile();
     } else {
         if (is_string($qtiResource) === true) {
             $filePath = $qtiResource;
         } else {
             throw new InvalidArgumentException("The 'qtiResource' argument must be a string or a taoQTI_models_classes_QTI_Resource object.");
         }
     }
     $resourcePathinfo = pathinfo($filePath);
     if (empty($resourcePathinfo['dirname']) === false && $resourcePathinfo['dirname'] !== '.') {
         // The resource file is not at the root of the archive but in a sub-folder.
         // Let's copy it in the same way into the Test Content folder.
         $breadCrumb = $contentPath . $ds . str_replace('/', $ds, $resourcePathinfo['dirname']);
         $breadCrumb = rtrim($breadCrumb, $ds);
         $finalName = empty($rename) === true ? $resourcePathinfo['filename'] . '.' . $resourcePathinfo['extension'] : $rename;
         $finalPath = $breadCrumb . $ds . $finalName;
         if (is_dir($breadCrumb) === false && @mkdir($breadCrumb, 0770, true) === false) {
             throw new common_Exception("An error occured while creating the '{$breadCrumb}' sub-directory where the QTI resource had to be copied.");
         }
     } else {
         // The resource file is at the root of the archive.
         // Overwrite template test.xml (created by self::createContent() method above) file with the new one.
         $finalName = empty($rename) === true ? $resourcePathinfo['filename'] . '.' . $resourcePathinfo['extension'] : $rename;
         $finalPath = $contentPath . $ds . $finalName;
     }
     if ($copy === true) {
         $origin = str_replace('/', $ds, $origin);
         $origin = rtrim($origin, $ds);
         $sourcePath = $origin . $ds . str_replace('/', $ds, $filePath);
         if (is_readable($sourcePath) === false || tao_helpers_File::copy($sourcePath, $finalPath) === false) {
             throw new common_Exception("An error occured while copying the QTI resource from '{$sourcePath}' to '{$finalPath}'.");
         }
     }
     return $finalPath;
 }
 /**
  *
  * @param string $initialVersion
  * @return string $versionUpdatedTo
  */
 public function update($initialVersion)
 {
     $currentVersion = $initialVersion;
     //migrate from 0.1 to 0.1.1
     if ($currentVersion == '0.1') {
         // mediaSources set in 0.2
         $currentVersion = '0.1.1';
     }
     if ($currentVersion == '0.1.1') {
         FileManager::setFileManagementModel(new SimpleFileManagement());
         // mediaSources unset in 0.2
         $currentVersion = '0.1.2';
     }
     if ($currentVersion == '0.1.2') {
         //add alt text to media manager
         $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'alt_text.rdf';
         $adapter = new \tao_helpers_data_GenerisAdapterRdf();
         if ($adapter->import($file)) {
             $currentVersion = '0.1.3';
         } else {
             \common_Logger::w('Import failed for ' . $file);
         }
     }
     if ($currentVersion == '0.1.3') {
         OntologyUpdater::correctModelId(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'alt_text.rdf');
         $currentVersion = '0.1.4';
     }
     if ($currentVersion == '0.1.4') {
         //modify config files due to the new interfaces relation
         $tao = \common_ext_ExtensionsManager::singleton()->getExtensionById('tao');
         $tao->unsetConfig('mediaManagementSources');
         $tao->unsetConfig('mediaBrowserSources');
         TaoMediaService::singleton()->addMediaSource(new MediaSource());
         //modify links in item content
         $service = \taoItems_models_classes_ItemsService::singleton();
         $items = $service->getAllByModel('http://www.tao.lu/Ontologies/TAOItem.rdf#QTI');
         foreach ($items as $item) {
             $itemContent = $service->getItemContent($item);
             $itemContent = preg_replace_callback('/src="mediamanager\\/([^"]+)"/', function ($matches) {
                 $mediaClass = MediaService::singleton()->getRootClass();
                 $medias = $mediaClass->searchInstances(array(MEDIA_LINK => $matches[1]), array('recursive' => true));
                 $media = array_pop($medias);
                 $uri = '';
                 if (!is_null($media) && $media->exists()) {
                     $uri = \tao_helpers_Uri::encode($media->getUri());
                 }
                 return 'src="taomedia://mediamanager/' . $uri . '"';
             }, $itemContent);
             $itemContent = preg_replace_callback('/src="local\\/([^"]+)"/', function ($matches) {
                 return 'src="' . $matches[1] . '"';
             }, $itemContent);
             $service->setItemContent($item, $itemContent);
         }
         $currentVersion = '0.2.0';
     }
     if ($currentVersion === '0.2.0') {
         $accessService = \funcAcl_models_classes_AccessService::singleton();
         //revoke access right to back office
         $backOffice = new \core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAO.rdf#BackOfficeRole');
         $accessService->revokeExtensionAccess($backOffice, 'taoMediaManager');
         //grant access right to media manager
         $mediaManager = new \core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAOMedia.rdf#MediaManagerRole');
         $accessService->grantExtensionAccess($mediaManager, 'taoMediaManager');
         $currentVersion = '0.2.1';
     }
     if ($currentVersion === '0.2.1') {
         //include mediamanager into globalmanager
         $mediaManager = new \core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAOMedia.rdf#MediaManagerRole');
         $globalManager = new \core_kernel_Classes_Resource('http://www.tao.lu/Ontologies/TAO.rdf#GlobalManagerRole');
         \tao_models_classes_RoleService::singleton()->includeRole($globalManager, $mediaManager);
         $currentVersion = '0.2.2';
     }
     if ($currentVersion === '0.2.2') {
         //copy file from /media to data/taoMediaManager/media and delete /media
         $dataPath = FILES_PATH . 'taoMediaManager' . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR;
         $dir = dirname(dirname(__DIR__)) . '/media';
         if (file_exists($dir)) {
             if (\tao_helpers_File::copy($dir, $dataPath)) {
                 $it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
                 $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
                 foreach ($files as $file) {
                     if ($file->isDir()) {
                         rmdir($file->getRealPath());
                     } else {
                         unlink($file->getRealPath());
                     }
                 }
                 rmdir($dir);
                 $currentVersion = '0.2.3';
             }
         } else {
             $currentVersion = '0.2.3';
         }
     }
     if ($currentVersion === '0.2.3') {
         $accessService = \funcAcl_models_classes_AccessService::singleton();
         //grant access to item author
         $itemAuthor = new \core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAOItem.rdf#ItemAuthor');
         $accessService->grantExtensionAccess($itemAuthor, 'taoMediaManager');
         $currentVersion = '0.2.4';
     }
     if ($currentVersion === '0.2.4') {
         $mediaClass = MediaService::singleton()->getRootClass();
         $fileManager = FileManager::getFileManagementModel();
         foreach ($mediaClass->getInstances(true) as $media) {
             $fileLink = $media->getUniquePropertyValue(new \core_kernel_classes_Property(MEDIA_LINK));
             $fileLink = $fileLink instanceof \core_kernel_classes_Resource ? $fileLink->getUri() : (string) $fileLink;
             $filePath = $fileManager->retrieveFile($fileLink);
             $mimeType = \tao_helpers_File::getMimeType($filePath);
             $mimeType = $mimeType === 'application/xhtml+xml' ? 'application/qti+xml' : $mimeType;
             $media->setPropertyValue(new \core_kernel_classes_Property(MEDIA_MIME_TYPE), $mimeType);
         }
         $currentVersion = '0.2.5';
     }
     if ($currentVersion === '0.2.5') {
         $fileManager = FileManager::getFileManagementModel();
         $iterator = new \core_kernel_classes_ResourceIterator(array(MediaService::singleton()->getRootClass()));
         foreach ($iterator as $media) {
             $fileLink = $media->getUniquePropertyValue(new \core_kernel_classes_Property(MEDIA_LINK));
             $fileLink = $fileLink instanceof \core_kernel_classes_Resource ? $fileLink->getUri() : (string) $fileLink;
             $filePath = $fileManager->retrieveFile($fileLink);
             try {
                 SharedStimulusImporter::isValidSharedStimulus($filePath);
                 $media->editPropertyValues(new \core_kernel_classes_Property(MEDIA_MIME_TYPE), 'application/qti+xml');
             } catch (\Exception $e) {
                 $mimeType = \tao_helpers_File::getMimeType($filePath);
                 $media->editPropertyValues(new \core_kernel_classes_Property(MEDIA_MIME_TYPE), $mimeType);
             }
         }
         $currentVersion = '0.3.0';
     }
     $this->skip('0.3.0', '0.5.1');
 }
 /**
  * Copy the resources (e.g. images) of the test to the private compilation directory.
  */
 protected function copyPrivateResources()
 {
     $testService = taoQtiTest_models_classes_QtiTestService::singleton();
     $testPath = $testService->getTestContent($this->getResource())->getAbsolutePath();
     $subContent = tao_helpers_File::scandir($testPath, array('recursive' => false, 'absolute' => true));
     $privateDirPath = $this->getPrivateDirectory()->getPath();
     // Recursive copy of each root level resources.
     foreach ($subContent as $subC) {
         tao_helpers_File::copy($subC, $privateDirPath . basename($subC));
     }
 }
 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;
 }
Example #8
0
 public function actionChangeCode()
 {
     $this->outVerbose("Changing code of locale '" . $this->options['language'] . "' to '" . $this->options['targetLanguage'] . "' for extension '" . $this->options['extension'] . "'...");
     // First we copy the old locale to a new directory named as 'targetLanguage'.
     $sourceLocaleDir = $this->options['output'] . DIRECTORY_SEPARATOR . $this->options['language'];
     $destLocaleDir = $this->options['output'] . DIRECTORY_SEPARATOR . $this->options['targetLanguage'];
     if (!tao_helpers_File::copy($sourceLocaleDir, $destLocaleDir, true, true)) {
         $this->err("Locale '" . $this->options['language'] . "' could not be copied to locale '" . $this->options['targetLanguage'] . "'.");
     }
     // We now apply transformations to the new locale.
     foreach (scandir($destLocaleDir) as $f) {
         $sourceLang = $this->options['language'];
         $destLang = $this->options['targetLanguage'];
         $qSourceLang = preg_quote($sourceLang);
         $qDestLang = preg_quote($destLang);
         if (!is_dir($f) && $f[0] != '.') {
             if ($f == 'messages.po') {
                 // Change the language tag in the PO file.
                 $pattern = "/Language: {$qSourceLang}/u";
                 $count = 0;
                 $content = file_get_contents($destLocaleDir . DIRECTORY_SEPARATOR . 'messages.po');
                 $newFileContent = preg_replace($pattern, "Language: {$destLang}", $content, -1, $count);
                 if ($count == 1) {
                     $this->outVerbose("Language tag '{$destLang}' applied to messages.po.");
                     file_put_contents($destLocaleDir . DIRECTORY_SEPARATOR . 'messages.po', $newFileContent);
                 } else {
                     $this->err("Could not change language tag in messages.po.");
                 }
             } else {
                 if ($f == 'messages_po.js') {
                     // Change the language tag in comments.
                     // Change the langCode JS variable.
                     $pattern = "/var langCode = '{$qSourceLang}';/u";
                     $count1 = 0;
                     $content = file_get_contents($destLocaleDir . DIRECTORY_SEPARATOR . 'messages_po.js');
                     $newFileContent = preg_replace($pattern, "var langCode = '{$destLang}';", $content, -1, $count1);
                     $pattern = "|/\\* lang: {$qSourceLang} \\*/|u";
                     $count2 = 0;
                     $newFileContent = preg_replace($pattern, "/* lang: {$destLang} */", $newFileContent, -1, $count2);
                     if ($count1 + $count2 == 2) {
                         $this->outVerbose("Language tag '{$destLang}' applied to messages_po.js");
                         file_put_contents($destLocaleDir . DIRECTORY_SEPARATOR . 'messages_po.js', $newFileContent);
                     } else {
                         $this->err("Could not change language tag in messages_po.js");
                     }
                 } else {
                     if ($f == 'lang.rdf') {
                         // Change <![CDATA[XX]]>
                         // Change http://www.tao.lu/Ontologies/TAO.rdf#LangXX
                         $pattern = "/<!\\[CDATA\\[{$qSourceLang}\\]\\]>/u";
                         $count1 = 0;
                         $content = file_get_contents($destLocaleDir . DIRECTORY_SEPARATOR . 'lang.rdf');
                         $newFileContent = preg_replace($pattern, "<![CDATA[{$destLang}]]>", $content, -1, $count1);
                         $pattern = "|http://www.tao.lu/Ontologies/TAO.rdf#Lang{$qSourceLang}|u";
                         $count2 = 0;
                         $newFileContent = preg_replace($pattern, "http://www.tao.lu/Ontologies/TAO.rdf#Lang{$destLang}", $newFileContent, -1, $count2);
                         $pattern = '/xml:lang="EN"/u';
                         $count3 = 0;
                         $newFileContent = preg_replace($pattern, 'xml:lang="en-US"', $newFileContent, -1, $count3);
                         if ($count1 + $count2 + $count3 == 3) {
                             $this->outVerbose("Language tag '{$destLang}' applied to lang.rdf");
                             file_put_contents($destLocaleDir . DIRECTORY_SEPARATOR . 'lang.rdf', $newFileContent);
                         } else {
                             $this->err("Could not change language tag in lang.rdf");
                         }
                     } else {
                         // Check for a .rdf extension.
                         $infos = pathinfo($destLocaleDir . DIRECTORY_SEPARATOR . $f);
                         if (isset($infos['extension']) && $infos['extension'] == 'rdf') {
                             // Change annotations @sourceLanguage and @targetLanguage
                             // Change xml:lang
                             $pattern = "/@sourceLanguage EN/u";
                             $content = file_get_contents($destLocaleDir . DIRECTORY_SEPARATOR . $f);
                             $newFileContent = preg_replace($pattern, "@sourceLanguage en-US", $content);
                             $pattern = "/@targetLanguage {$qSourceLang}/u";
                             $newFileContent = preg_replace($pattern, "@targetLanguage {$destLang}", $newFileContent);
                             $pattern = '/xml:lang="' . $qSourceLang . '"/u';
                             $newFileContent = preg_replace($pattern, 'xml:lang="' . $destLang . '"', $newFileContent);
                             $this->outVerbose("Language tag '{$destLang}' applied to {$f}");
                             file_put_contents($destLocaleDir . DIRECTORY_SEPARATOR . $f, $newFileContent);
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * (non-PHPdoc)
  * @see \oat\tao\model\media\MediaManagement::add
  */
 public function add($source, $fileName, $parent)
 {
     if (!\tao_helpers_File::securityCheck($fileName, true)) {
         throw new \common_Exception('Unsecured filename "' . $fileName . '"');
     }
     $sysPath = $this->getSysPath($parent . $fileName);
     if (!tao_helpers_File::copy($source, $sysPath)) {
         throw new common_exception_Error('Unable to move file ' . $source);
     }
     $fileData = $this->getFileInfo('/' . $parent . $fileName, array());
     return $fileData;
 }
 /**
  * Starts the import based on the form
  *
  * @param \core_kernel_classes_Class $class
  * @param \tao_helpers_form_Form $form
  * @return \common_report_Report $report
  */
 public function import($class, $form)
 {
     //as upload may be called multiple times, we remove the session lock as soon as possible
     session_write_close();
     try {
         $file = $form->getValue('source');
         $service = MediaService::singleton();
         $classUri = $class->getUri();
         if (is_null($this->instanceUri) || $this->instanceUri === $classUri) {
             //if the file is a zip do a zip import
             if ($file['type'] !== 'application/zip') {
                 try {
                     self::isValidSharedStimulus($file['uploaded_file']);
                     $filepath = $file['uploaded_file'];
                     $name = $file['name'];
                     if (!$service->createMediaInstance($filepath, $classUri, \tao_helpers_Uri::decode($form->getValue('lang')), $name, 'application/qti+xml')) {
                         $report = \common_report_Report::createFailure(__('Fail to import Shared Stimulus'));
                     } else {
                         $report = \common_report_Report::createSuccess(__('Shared Stimulus imported successfully'));
                     }
                 } catch (XmlStorageException $e) {
                     // The shared stimulus is not qti compliant, display error
                     $report = \common_report_Report::createFailure($e->getMessage());
                 }
             } else {
                 $report = $this->zipImporter->import($class, $form);
             }
         } else {
             if ($file['type'] !== 'application/zip') {
                 self::isValidSharedStimulus($file['uploaded_file']);
                 $filepath = $file['uploaded_file'];
                 if (in_array($file['type'], array('application/xml', 'text/xml'))) {
                     $name = basename($file['name'], 'xml');
                     $name .= 'xhtml';
                     $filepath = dirname($file['name']) . '/' . $name;
                     \tao_helpers_File::copy($file['uploaded_file'], $filepath);
                 }
                 if (!$service->editMediaInstance($filepath, $this->instanceUri, \tao_helpers_Uri::decode($form->getValue('lang')))) {
                     $report = \common_report_Report::createFailure(__('Fail to edit shared stimulus'));
                 } else {
                     $report = \common_report_Report::createSuccess(__('Shared Stimulus edited successfully'));
                 }
             } else {
                 $report = $this->zipImporter->edit(new \core_kernel_classes_Resource($this->instanceUri), $form);
             }
         }
         return $report;
     } catch (\Exception $e) {
         $report = \common_report_Report::createFailure($e->getMessage());
         return $report;
     }
 }
 /**
  * Clone a QTI Test Resource.
  *
  * @param core_kernel_classes_Resource $source The resource to be cloned.
  * @param core_kernel_classes_Resource $destination An existing resource to be filled as the clone of $source.
  */
 public function cloneContent(core_kernel_classes_Resource $source, core_kernel_classes_Resource $destination)
 {
     $contentProperty = new core_kernel_classes_Property(TEST_TESTCONTENT_PROP);
     $existingDir = new core_kernel_file_File($source->getUniquePropertyValue($contentProperty));
     $service = taoQtiTest_models_classes_QtiTestService::singleton();
     $dir = $service->createContent($destination, false);
     if ($existingDir->fileExists()) {
         tao_helpers_File::copy($existingDir->getAbsolutePath(), $dir->getAbsolutePath(), true, false);
     } else {
         common_Logger::w('Test "' . $source->getUri() . '" had no content, nothing to clone');
     }
 }
 protected function cloneItemContent($source, $destination, $property)
 {
     $fileNameProp = new core_kernel_classes_Property(PROPERTY_FILE_FILENAME);
     foreach ($source->getPropertyValuesCollection($property)->getIterator() as $propertyValue) {
         $file = new core_kernel_versioning_File($propertyValue->getUri());
         $repo = $file->getRepository();
         $relPath = basename($file->getAbsolutePath());
         if (!empty($relPath)) {
             $newPath = tao_helpers_File::concat(array($this->getItemFolder($destination), $relPath));
             common_Logger::i('copy ' . dirname($file->getAbsolutePath()) . ' to ' . dirname($newPath));
             tao_helpers_File::copy(dirname($file->getAbsolutePath()), dirname($newPath), true);
             if (file_exists($newPath)) {
                 $subpath = substr($newPath, strlen($repo->getPath()));
                 $newFile = $repo->createFile((string) $file->getOnePropertyValue($fileNameProp), dirname($subpath) . '/');
                 $destination->setPropertyValue($property, $newFile->getUri());
                 $newFile->add(true, true);
                 $newFile->commit('Clone of ' . $source->getUri(), true);
             }
         }
     }
 }
Example #13
0
 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);
 }
 /**
  * Enables you to get the content of an item, 
  * usually an xml string
  *
  * @deprecated use \oat\taoQtiItem\model\qti\Service::getDataItemByRdfItem instead
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param  Resource item
  * @param  boolean preview
  * @param  string lang
  * @return string
  */
 public function getItemContent(core_kernel_classes_Resource $item, $lang = '')
 {
     $returnValue = (string) '';
     common_Logger::i('Get itemContent for item ' . $item->getUri());
     if (!is_null($item)) {
         $itemContent = null;
         if (empty($lang)) {
             $itemContents = $item->getPropertyValuesCollection($this->itemContentProperty);
         } else {
             $itemContents = $item->getPropertyValuesByLg($this->itemContentProperty, $lang);
         }
         if ($itemContents->count() > 0) {
             $itemContent = $itemContents->get(0);
         } else {
             if (!empty($lang)) {
                 $itemContents = $item->getPropertyValuesCollection($this->itemContentProperty);
                 if ($itemContents->count() > 0) {
                     $itemContent = $itemContents->get(0);
                     $this->setDefaultItemContent($item, $itemContent, $lang);
                     tao_helpers_File::copy($this->getItemFolder($item, DEFAULT_LANG), $this->getItemFolder($item, $lang));
                 }
             }
         }
         if (!is_null($itemContent) && $this->isItemModelDefined($item)) {
             if (core_kernel_file_File::isFile($itemContent)) {
                 $file = new core_kernel_file_File($itemContent->getUri());
                 $returnValue = file_get_contents($file->getAbsolutePath());
                 if ($returnValue == false) {
                     common_Logger::w('File ' . $file->getAbsolutePath() . ' not found for fileressource ' . $itemContent->getUri());
                 }
             }
         } else {
             common_Logger::w('No itemContent for item ' . $item->getUri());
         }
     }
     return (string) $returnValue;
 }
 /**
  * Upload a file to the item directory
  * 
  * @throws common_exception_MissingParameter
  */
 public function upload()
 {
     //as upload may be called multiple times, we remove the session lock as soon as possible
     try {
         session_write_close();
         if ($this->hasRequestParameter('uri')) {
             $itemUri = $this->getRequestParameter('uri');
             $item = new core_kernel_classes_Resource($itemUri);
         }
         if ($this->hasRequestParameter('lang')) {
             $itemLang = $this->getRequestParameter('lang');
         }
         if (!$this->hasRequestParameter('path')) {
             throw new common_exception_MissingParameter('path', __METHOD__);
         }
         if (!$this->hasRequestParameter('filters')) {
             throw new common_exception_MissingParameter('filters', __METHOD__);
         }
         $filters = explode(',', $this->getRequestParameter('filters'));
         $resolver = new ItemMediaResolver($item, $itemLang);
         $asset = $resolver->resolve($this->getRequestParameter('relPath'));
         $file = tao_helpers_Http::getUploadedFile('content');
         $fileTmpName = $file['tmp_name'] . '_' . $file['name'];
         if (!tao_helpers_File::copy($file['tmp_name'], $fileTmpName)) {
             throw new common_exception_Error('impossible to copy ' . $file['tmp_name'] . ' to ' . $fileTmpName);
         }
         $mime = \tao_helpers_File::getMimeType($fileTmpName);
         if (in_array($mime, $filters)) {
             $filedata = $asset->getMediaSource()->add($fileTmpName, $file['name'], $asset->getMediaIdentifier());
         } else {
             throw new \oat\tao\helpers\FileUploadException('The file you tried to upload is not valid');
         }
         $this->returnJson($filedata);
         return;
     } catch (\oat\tao\model\accessControl\data\PermissionException $e) {
         $message = $e->getMessage();
     } catch (\oat\tao\helpers\FileUploadException $e) {
         $message = $e->getMessage();
     } catch (common_Exception $e) {
         common_Logger::w($e->getMessage());
         $message = _('Unable to upload file');
     }
     $this->returnJson(array('error' => $message));
 }
 /**
  * Import a QTI Test and its dependent Items into the TAO Platform.
  *
  * @param core_kernel_classes_Class $targetClass The RDFS Class where Ontology resources must be created.
  * @param oat\taoQtiItem\model\qti\Resource $qtiTestResource The QTI Test Resource representing the IMS QTI Test to be imported.
  * @param taoQtiTest_models_classes_ManifestParser $manifestParser The parser used to retrieve the IMS Manifest.
  * @param string $folder The absolute path to the folder where the IMS archive containing the test content
  * @return common_report_Report A report about how the importation behaved.
  */
 protected function importTest(core_kernel_classes_Class $targetClass, Resource $qtiTestResource, taoQtiTest_models_classes_ManifestParser $manifestParser, $folder)
 {
     $itemImportService = ImportService::singleton();
     $itemService = taoItems_models_classes_ItemsService::singleton();
     $testClass = $targetClass;
     // Create an RDFS resource in the knowledge base that will hold
     // the information about the imported QTI Test.
     $testResource = $this->createInstance($testClass);
     $qtiTestModelResource = new core_kernel_classes_Resource(INSTANCE_TEST_MODEL_QTI);
     $modelProperty = new core_kernel_classes_Property(PROPERTY_TEST_TESTMODEL);
     $testResource->editPropertyValues($modelProperty, $qtiTestModelResource);
     // Create the report that will hold information about the import
     // of $qtiTestResource in TAO.
     $report = new common_report_Report(common_report_Report::TYPE_INFO);
     // The class where the items that belong to the test will be imported.
     $itemClass = new core_kernel_classes_Class(TAO_ITEM_CLASS);
     $targetClass = $itemClass->createSubClass($testResource->getLabel());
     // Load and validate the manifest
     $qtiManifestParser = new taoQtiTest_models_classes_ManifestParser($folder . 'imsmanifest.xml');
     $qtiManifestParser->validate();
     // Set up $report with useful information for client code (especially for rollback).
     $reportCtx = new stdClass();
     $reportCtx->manifestResource = $qtiTestResource;
     $reportCtx->rdfsResource = $testResource;
     $reportCtx->itemClass = $targetClass;
     $reportCtx->items = array();
     $report->setData($reportCtx);
     // Expected test.xml file location.
     $expectedTestFile = $folder . str_replace('/', DIRECTORY_SEPARATOR, $qtiTestResource->getFile());
     // Already imported test items (qti xml file paths).
     $alreadyImportedTestItemFiles = array();
     // -- Check if the file referenced by the test QTI resource exists.
     if (is_readable($expectedTestFile) === false) {
         $report->add(common_report_Report::createFailure(__('No file found at location "%s".', $qtiTestResource->getFile())));
     } else {
         // -- Load the test in a QTISM flavour.
         $testDefinition = new XmlDocument();
         try {
             $testDefinition->load($expectedTestFile, true);
             // -- Load all items related to test.
             $itemError = false;
             // discover test's base path.
             $dependencies = taoQtiTest_helpers_Utils::buildAssessmentItemRefsTestMap($testDefinition, $manifestParser, $folder);
             if (count($dependencies) > 0) {
                 foreach ($dependencies as $assessmentItemRefId => $qtiDependency) {
                     if ($qtiDependency !== false) {
                         if (Resource::isAssessmentItem($qtiDependency->getType())) {
                             $qtiFile = $folder . str_replace('/', DIRECTORY_SEPARATOR, $qtiDependency->getFile());
                             // Skip if $qtiFile already imported (multiple assessmentItemRef "hrefing" the same file).
                             if (array_key_exists($qtiFile, $alreadyImportedTestItemFiles) === false) {
                                 $itemReport = $itemImportService->importQTIFile($qtiFile, $targetClass);
                                 $rdfItem = $itemReport->getData();
                                 if ($rdfItem) {
                                     $itemPath = taoItems_models_classes_ItemsService::singleton()->getItemFolder($rdfItem);
                                     foreach ($qtiDependency->getAuxiliaryFiles() as $auxResource) {
                                         // $auxResource is a relativ URL, so we need to replace the slashes with directory separators
                                         $auxPath = $folder . str_replace('/', DIRECTORY_SEPARATOR, $auxResource);
                                         // does the file referenced by $auxPath exist?
                                         if (is_readable($auxPath) === true) {
                                             $relPath = helpers_File::getRelPath($qtiFile, $auxPath);
                                             $destPath = $itemPath . $relPath;
                                             tao_helpers_File::copy($auxPath, $destPath, true);
                                         } else {
                                             $msg = __('Auxiliary file not found at location "%s".', $auxResource);
                                             $itemReport->add(new common_report_Report(common_report_Report::TYPE_WARNING, $msg));
                                         }
                                     }
                                     $reportCtx->items[$assessmentItemRefId] = $rdfItem;
                                     $alreadyImportedTestItemFiles[$qtiFile] = $rdfItem;
                                     $itemReport->setMessage(__('IMS QTI Item referenced as "%s" in the IMS Manifest file successfully imported.', $qtiDependency->getIdentifier()));
                                 } else {
                                     $itemReport->setType(common_report_Report::TYPE_ERROR);
                                     $itemReport->setMessage(__('IMS QTI Item referenced as "%s" in the IMS Manifest file could not be imported.', $qtiDependency->getIdentifier()));
                                     $itemError = $itemError === false ? true : $itemError;
                                 }
                                 $report->add($itemReport);
                             } else {
                                 $reportCtx->items[$assessmentItemRefId] = $alreadyImportedTestItemFiles[$qtiFile];
                             }
                         }
                     } else {
                         $msg = __('The dependency to the IMS QTI AssessmentItemRef "%s" in the IMS Manifest file could not be resolved.', $assessmentItemRefId);
                         $report->add(common_report_Report::createFailure($msg));
                         $itemError = $itemError === false ? true : $itemError;
                     }
                 }
                 // If items did not produce errors, we import the test definition.
                 if ($itemError === false) {
                     common_Logger::i('Importing test...');
                     // Second step is to take care of the test definition and the related media (auxiliary files).
                     // 1. Import test definition (i.e. the QTI-XML Test file).
                     $testContent = $this->importTestDefinition($testResource, $testDefinition, $qtiTestResource, $reportCtx->items, $folder, $report);
                     if ($testContent !== false) {
                         // 2. Import test auxilliary files (e.g. stylesheets, images, ...).
                         $this->importTestAuxiliaryFiles($testContent, $qtiTestResource, $folder, $report);
                         // 3. Give meaningful names to resources.
                         $testTitle = $testDefinition->getDocumentComponent()->getTitle();
                         $testResource->setLabel($testDefinition->getDocumentComponent()->getTitle());
                         $targetClass->setLabel($testDefinition->getDocumentComponent()->getTitle());
                     }
                 } else {
                     $msg = __("One or more dependent IMS QTI Items could not be imported.");
                     $report->add(common_report_Report::createFailure($msg));
                 }
             } else {
                 // No depencies found (i.e. no item resources bound to the test).
                 $msg = __("No reference to any IMS QTI Item found.");
                 $report->add(common_report_Report::createFailure($msg));
             }
         } catch (StorageException $e) {
             // Source of the exception = $testDefinition->load()
             // What is the reason ?
             $finalErrorString = '';
             $eStrs = array();
             if (($libXmlErrors = $e->getErrors()) !== null) {
                 foreach ($libXmlErrors as $libXmlError) {
                     $eStrs[] = __('XML error at line %1$d column %2$d "%3$s".', $libXmlError->line, $libXmlError->column, trim($libXmlError->message));
                 }
             }
             $finalErrorString = implode("\n", $eStrs);
             if (empty($finalErrorString) === true) {
                 // Not XML malformation related. No info from LibXmlErrors extracted.
                 if (($previous = $e->getPrevious()) != null) {
                     // Useful information could be found here.
                     $finalErrorString = $previous->getMessage();
                     if ($previous instanceof UnmarshallingException) {
                         $domElement = $previous->getDOMElement();
                         $finalErrorString = __('Inconsistency at line %1d:', $domElement->getLineNo()) . ' ' . $previous->getMessage();
                     }
                 } else {
                     $finalErrorString = __("Unknown error.");
                 }
             }
             $msg = __("Error found in the IMS QTI Test:\n%s", $finalErrorString);
             $report->add(common_report_Report::createFailure($msg));
         }
     }
     if ($report->containsError() === false) {
         $report->setType(common_report_Report::TYPE_SUCCESS);
         $msg = __("IMS QTI Test referenced as \"%s\" in the IMS Manifest file successfully imported.", $qtiTestResource->getIdentifier());
         $report->setMessage($msg);
     } else {
         $report->setType(common_report_Report::TYPE_ERROR);
         $msg = __("The IMS QTI Test referenced as \"%s\" in the IMS Manifest file could not be imported.", $qtiTestResource->getIdentifier());
         $report->setMessage($msg);
     }
     return $report;
 }
Example #17
0
 /**
  * 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 the resources (e.g. images) of the test to the private compilation directory.
  */
 protected function copyPrivateResources()
 {
     $testService = taoQtiTest_models_classes_QtiTestService::singleton();
     $testPath = $testService->getTestContent($this->getResource())->getAbsolutePath();
     $subContent = tao_helpers_File::scandir($testPath, array('recursive' => false, 'absolute' => true));
     $privateDirPath = $this->getPrivateDirectory()->getPath();
     // Recursive copy of each root level resources.
     foreach ($subContent as $subC) {
         tao_helpers_File::copy($subC, $privateDirPath . basename($subC));
     }
     // Append the qti_base.css to copied files.
     $ds = DIRECTORY_SEPARATOR;
     $qtiBaseStylesheetPath = dirname(__FILE__) . $ds . '..' . $ds . '..' . $ds . 'views' . $ds . 'css' . $ds . 'qti_base.css';
     $qtiBaseStylesheetDestPath = $privateDirPath . trim($this->getExtraPath(), $ds) . $ds . 'qti_base.css';
     tao_helpers_File::copy($qtiBaseStylesheetPath, $qtiBaseStylesheetDestPath);
 }