public function __invoke($params)
 {
     $service = new PortableElementService();
     $service->setServiceLocator(ServiceManager::getServiceManager());
     $sourceDirectory = $this->getSourceDirectory();
     if (empty($sourceDirectory)) {
         return $this->createFailure('the source directory is empty');
     }
     if (!is_readable($sourceDirectory)) {
         return $this->createFailure('the source directory does not exists or is not readable ' . $sourceDirectory);
     }
     try {
         $model = $service->getValidPortableElementFromDirectorySource($sourceDirectory);
         if (!empty($params)) {
             $minRequiredVersion = $params[0];
             // if the minimal required version number string "x.y.z" is given in the parameter, the new target version should be equal or higher than it
             if (version_compare($model->getVersion(), $minRequiredVersion) < 0) {
                 return $this->createFailure('the version in manifest "' . $model->getVersion() . '" cannot be lower than the given minimum required version "' . $minRequiredVersion . '"', $model);
             }
         }
         $service->registerFromDirectorySource($sourceDirectory);
     } catch (PortableElementVersionIncompatibilityException $e) {
         return $this->createFailure('incompatible version: ' . $e->getMessage(), $model);
     }
     return Report::createSuccess('registered portable element "' . $model->getTypeIdentifier() . '" in version "' . $model->getVersion() . '""');
 }
 public function __invoke($params)
 {
     // recreate languages
     $modelCreator = new \tao_install_utils_ModelCreator(LOCAL_NAMESPACE);
     $models = $modelCreator->getLanguageModels();
     foreach ($models as $ns => $modelFiles) {
         foreach ($modelFiles as $file) {
             $modelCreator->insertLocalModel($file);
         }
     }
     OntologyUpdater::syncModels();
     // reapply access rights
     $exts = \common_ext_ExtensionsManager::singleton()->getInstalledExtensions();
     foreach ($exts as $ext) {
         $installer = new \tao_install_ExtensionInstaller($ext);
         $installer->installManagementRole();
         $installer->applyAccessRules();
     }
     // recreate admin
     if (count($params) >= 2) {
         $login = array_shift($params);
         $password = array_shift($params);
         $sysAdmin = $this->getResource(INSTANCE_ROLE_SYSADMIN);
         $userClass = $this->getClass(CLASS_TAO_USER);
         \core_kernel_users_Service::singleton()->addUser($login, $password, $sysAdmin, $userClass);
     }
     // empty cache
     \common_cache_FileCache::singleton()->purge();
     return \common_report_Report::createSuccess('All done');
 }
 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 export($options = array())
 {
     if (!$this->containsItem()) {
         $report = parent::export($options);
         if (!$report->containsError()) {
             $this->exportManifest($options);
         }
         return $report;
     }
     return \common_report_Report::createSuccess();
 }
 /**
  * Short description of method importQTIFile
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param $qtiFile
  * @param core_kernel_classes_Class $itemClass
  * @param bool $validate
  * @param core_kernel_versioning_Repository $repository unused
  * @throws \common_Exception
  * @throws \common_ext_ExtensionException
  * @throws common_exception_Error
  * @return common_report_Report
  */
 public function importQTIFile($qtiFile, core_kernel_classes_Class $itemClass, $validate = true, core_kernel_versioning_Repository $repository = null)
 {
     $report = null;
     try {
         $qtiModel = $this->createQtiItemModel($qtiFile, $validate);
         $rdfItem = $this->createRdfItem($itemClass, $qtiModel);
         $report = \common_report_Report::createSuccess(__('The IMS QTI Item was successfully imported.'), $rdfItem);
     } catch (ValidationException $ve) {
         $report = \common_report_Report::createFailure(__('The IMS QTI Item could not be imported.'));
         $report->add($ve->getReport());
     }
     return $report;
 }
 public function __invoke($params)
 {
     $run = false;
     if (!empty($params) && $params[0] === 'run') {
         $run = true;
     }
     \common_ext_ExtensionsManager::singleton()->getExtensionById('taoQtiItem');
     $fs = \taoItems_models_classes_ItemsService::singleton()->getDefaultFileSource();
     $itemUpdater = new ItemFixTextReaderDefaultValue($fs->getPath());
     $res = $itemUpdater->update($run);
     if ($run) {
         return \common_report_Report::createSuccess('Item fixed ' . count($res));
     } else {
         return \common_report_Report::createInfo('Item to be fixed ' . count($res));
     }
 }
 /**
  * Main method to import Iterator data to Ontology object
  *
  * @param array $data
  * @param boolean $dryrun If set to true no data will be written
  * @return \common_report_Report
  */
 public function import(array $data, $dryrun = false)
 {
     try {
         /** @var Injector[] $injectors */
         $injectors = $this->getInjectors();
     } catch (InconsistencyConfigException $e) {
         return \common_report_Report::createFailure('Config problem: ' . $e->getMessage());
     }
     // Global report
     $report = \common_report_Report::createInfo('Report of metadata import.');
     // Foreach line of dateSource
     foreach ($data as $uri => $dataSource) {
         try {
             // Check if resource exists
             $resource = $this->getResource($uri);
             if (!$resource->exists()) {
                 throw new MetadataImportException('Unable to find resource associated to uri : "' . $uri . '"');
             }
             $lineReport = \common_report_Report::createInfo('Report by line.');
             $dataSource = array_change_key_case($dataSource);
             // Foreach injector to map a target source
             /** @var Injector $injector */
             foreach ($injectors as $name => $injector) {
                 $injectorReport = null;
                 try {
                     $dataRead = $injector->read($dataSource);
                     $injector->write($resource, $dataRead, $dryrun);
                     $injectorReport = \common_report_Report::createSuccess('Injector "' . $name . '" successfully ran.');
                 } catch (MetadataInjectorReadException $e) {
                     $injectorReport = \common_report_Report::createFailure('Injector "' . $name . '" failed to run at read: ' . $e->getMessage());
                 } catch (MetadataInjectorWriteException $e) {
                     $injectorReport = \common_report_Report::createFailure('Injector "' . $name . '" failed to run at write: ' . $e->getMessage());
                 }
                 // Skip if there are no report (no data to read for this injector)
                 if (!is_null($injectorReport)) {
                     $lineReport->add($injectorReport);
                 }
             }
         } catch (MetadataImportException $e) {
             $lineReport = \common_report_Report::createFailure($e->getMessage());
         }
         $report->add($lineReport);
     }
     return $report;
 }
 /**
  * Short description of method importQTIFile
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param $qtiFile
  * @param core_kernel_classes_Class $itemClass
  * @param bool $validate
  * @param core_kernel_versioning_Repository $repository unused
  * @throws \common_Exception
  * @throws \common_ext_ExtensionException
  * @throws common_exception_Error
  * @return common_report_Report
  */
 public function importQTIFile($qtiFile, core_kernel_classes_Class $itemClass, $validate = true, core_kernel_versioning_Repository $repository = null, $extractApip = false)
 {
     $report = null;
     try {
         $qtiModel = $this->createQtiItemModel($qtiFile, $validate);
         $rdfItem = $this->createRdfItem($itemClass, $qtiModel);
         // If APIP content must be imported, just extract the apipAccessibility element
         // and store it along the qti.xml file.
         if ($extractApip === true) {
             $this->storeApip($qtiFile, $rdfItem);
         }
         $report = \common_report_Report::createSuccess(__('The IMS QTI Item was successfully imported.'), $rdfItem);
     } catch (ValidationException $ve) {
         $report = \common_report_Report::createFailure(__('The IMS QTI Item could not be imported.'));
         $report->add($ve->getReport());
     }
     return $report;
 }
Example #10
0
 /**
  * Imports the rdf file into the selected class
  * 
  * @param string $file
  * @param core_kernel_classes_Class $class
  * @return common_report_Report
  */
 private function flatImport($file, core_kernel_classes_Class $class)
 {
     $report = common_report_Report::createSuccess(__('Data imported successfully'));
     $graph = new EasyRdf_Graph();
     $graph->parseFile($file);
     // keep type property
     $map = array(RDF_PROPERTY => RDF_PROPERTY);
     foreach ($graph->resources() as $resource) {
         $map[$resource->getUri()] = common_Utils::getNewUri();
     }
     $format = EasyRdf_Format::getFormat('php');
     $data = $graph->serialise($format);
     foreach ($data as $subjectUri => $propertiesValues) {
         $resource = new core_kernel_classes_Resource($map[$subjectUri]);
         $subreport = $this->importProperties($resource, $propertiesValues, $map, $class);
         $report->add($subreport);
     }
     return $report;
 }
 public function testRenderNested()
 {
     $report = common_report_Report::createSuccess('Success!');
     $report->add(common_report_Report::createSuccess('Another success!'));
     $report->add(common_report_Report::createFailure('Failure!'));
     $expected = '<div class="feedback-success feedback-nesting-0 hierarchical tao-scope">';
     $expected .= '<span class="icon-success hierarchical-icon"></span>';
     $expected .= 'Success!';
     $expected .= '<div class="feedback-success feedback-nesting-1 leaf tao-scope">';
     $expected .= '<span class="icon-success leaf-icon"></span>';
     $expected .= 'Another success!';
     $expected .= '</div>';
     $expected .= '<div class="feedback-error feedback-nesting-1 leaf tao-scope">';
     $expected .= '<span class="icon-error leaf-icon"></span>';
     $expected .= 'Failure!';
     $expected .= '</div>';
     $expected .= '<p>';
     $expected .= '<button id="import-continue" class="btn-info"><span class="icon-right"></span>Continue</button>';
     $expected .= '</p>';
     $expected .= '</div>';
     $this->assertEquals($expected, tao_helpers_report_Rendering::render($report));
 }
 /**
  * (non-PHPdoc)
  * @see tao_models_classes_export_ExportHandler::export()
  */
 public function export($formValues, $destination)
 {
     $report = \common_report_Report::createSuccess();
     if (isset($formValues['filename'], $formValues['instances'])) {
         $instances = $formValues['instances'];
         if (count($instances) > 0) {
             $itemService = taoItems_models_classes_ItemsService::singleton();
             $fileName = $formValues['filename'] . '_' . time() . '.zip';
             $path = tao_helpers_File::concat(array($destination, $fileName));
             if (!tao_helpers_File::securityCheck($path, true)) {
                 throw new Exception('Unauthorized file name');
             }
             $zipArchive = new ZipArchive();
             if ($zipArchive->open($path, ZipArchive::CREATE) !== true) {
                 throw new Exception('Unable to create archive at ' . $path);
             }
             $manifest = null;
             foreach ($instances as $instance) {
                 $item = new core_kernel_classes_Resource($instance);
                 if ($itemService->hasItemModel($item, array(ItemModel::MODEL_URI))) {
                     $exporter = $this->createExporter($item, $zipArchive, $manifest);
                     $subReport = $exporter->export();
                     $manifest = $exporter->getManifest();
                     $report->add($subReport);
                 }
             }
             $zipArchive->close();
             $report->setData($path);
         }
     } else {
         if (!isset($formValues['filename'])) {
             common_Logger::w('Missing filename for export using ' . __CLASS__);
         }
         if (!isset($formValues['instances'])) {
             common_Logger::w('No instances selected for export using ' . __CLASS__);
         }
     }
     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;
 }
 /**
  * Starts the import based on the form
  *
  * @param \core_kernel_classes_Class $class
  * @param \tao_helpers_form_Form $form
  * @return \common_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');
         $resource = new core_kernel_classes_Class($form->getValue('classUri'));
         // unzip the file
         try {
             $directory = $this->extractArchive($file['uploaded_file']);
         } catch (\Exception $e) {
             return \common_report_Report::createFailure(__('Unable to extract the archive'));
         }
         // get list of directory in order to create classes
         $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::CURRENT_AS_FILEINFO | \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY);
         $service = MediaService::singleton();
         $language = $form->getValue('lang');
         $this->directoryMap = array(rtrim($directory, DIRECTORY_SEPARATOR) => $resource->getUri());
         /** @var $file \SplFileInfo */
         $report = \common_report_Report::createSuccess(__('Media imported successfully'));
         foreach ($iterator as $file) {
             if ($file->isFile()) {
                 \common_Logger::i('File ' . $file->getPathname());
                 if (isset($this->directoryMap[$file->getPath()])) {
                     $classUri = $this->directoryMap[$file->getPath()];
                 } else {
                     $classUri = $this->createClass($file->getPath());
                 }
                 $service->createMediaInstance($file->getRealPath(), $classUri, $language, $file->getFilename());
                 $report->add(\common_report_Report::createSuccess(__('Imported %s', substr($file->getRealPath(), strlen($directory)))));
             }
         }
         return $report;
     } catch (\Exception $e) {
         $report = \common_report_Report::createFailure($e->getMessage());
         return $report;
     }
 }
 /**
  * Export the dependent items into the ZIP archive.
  *
  * @return common_report_Report that contains An array of identifiers that were assigned to exported items into the IMS Manifest.
  */
 protected function exportItems()
 {
     $report = common_report_Report::createSuccess();
     $subReport = common_report_Report::createSuccess();
     $identifiers = array();
     $rootDir = $this->getTestService()->getQtiTestDir($this->getItem());
     $file = $this->getTestService()->getQtiTestFile($this->getItem());
     $extraPath = dirname($rootDir->getRelPath($file));
     $extraPath = trim($extraPath, '/');
     $extraReversePath = '';
     if (empty($extraPath) === false) {
         $n = count(explode('/', $extraPath));
         $parts = array();
         for ($i = 0; $i < $n; $i++) {
             $parts[] = '..';
         }
         $extraReversePath = implode('/', $parts) . '/';
     }
     foreach ($this->getItems() as $refIdentifier => $item) {
         $itemExporter = $this->createItemExporter($item);
         if (!in_array($itemExporter->buildIdentifier(), $identifiers)) {
             $identifiers[] = $itemExporter->buildIdentifier();
             $subReport = $itemExporter->export();
         }
         // Modify the reference to the item in the test definition.
         $newQtiItemXmlPath = $extraReversePath . '../../items/' . tao_helpers_Uri::getUniqueId($item->getUri()) . '/qti.xml';
         $itemRef = $this->getTestDocument()->getDocumentComponent()->getComponentByIdentifier($refIdentifier);
         $itemRef->setHref($newQtiItemXmlPath);
         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(__('Export error in test : %s', $this->getItem()->getLabel()));
         }
         $report->add($subReport);
     }
     $report->setData($identifiers);
     return $report;
 }
 public function testEditPackage()
 {
     $packageImporter = $this->getMockBuilder('oat\\taoMediaManager\\model\\SharedStimulusPackageImporter')->getMock();
     $instance = new \core_kernel_classes_Resource('http://fancyDomain.com/tao.rdf#fancyInstanceUri');
     $sharedImporter = new SharedStimulusImporter($instance->getUri());
     $filename = dirname(__DIR__) . '/sample/sharedStimulus/stimulusPackage.zip';
     $myClass = new \core_kernel_classes_Class('http://fancyDomain.com/tao.rdf#fancyUri');
     $file['type'] = 'application/zip';
     $file['uploaded_file'] = $filename;
     $form = $sharedImporter->getForm();
     $form->setValues(array('source' => $file, 'lang' => 'EN_en'));
     $returnReport = \common_report_Report::createSuccess('Success');
     $packageImporter->expects($this->once())->method('edit')->with($instance, $form)->willReturn($returnReport);
     $sharedImporter->setZipImporter($packageImporter);
     $report = $sharedImporter->import($myClass, $form);
     $this->assertEquals($returnReport->getMessage(), $report->getMessage(), __('Report message is wrong'));
     $this->assertEquals($returnReport->getType(), $report->getType(), __('Report should be success'));
 }
 /**
  * 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;
     }
 }
Example #18
0
 /**
  * Creates a report without title of the parsing result
  * @return common_report_Report
  */
 public function getReport()
 {
     if ($this->isValid()) {
         return common_report_Report::createSuccess('');
     } else {
         $report = new common_report_Report('');
         foreach ($this->getErrors() as $error) {
             $report->add(common_report_Report::createFailure($error['message']));
         }
         return $report;
     }
 }
 /**
  * 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') {
                 if (!$service->createMediaInstance($file["uploaded_file"], $classUri, \tao_helpers_Uri::decode($form->getValue('lang')), $file["name"])) {
                     $report = \common_report_Report::createFailure(__('Fail to import media'));
                 } else {
                     $report = \common_report_Report::createSuccess(__('Media imported successfully'));
                 }
             } else {
                 $zipImporter = new ZipImporter();
                 $report = $zipImporter->import($class, $form);
             }
         } else {
             if ($file['type'] !== 'application/zip') {
                 $service->editMediaInstance($file["uploaded_file"], $this->instanceUri, \tao_helpers_Uri::decode($form->getValue('lang')));
                 $report = \common_report_Report::createSuccess(__('Media imported successfully'));
             } else {
                 $report = \common_report_Report::createFailure(__('You can\'t upload a zip file as a media'));
             }
         }
         return $report;
     } catch (\Exception $e) {
         $report = \common_report_Report::createFailure($e->getMessage());
         return $report;
     }
 }
 /**
  * Overriden export from QTI items.
  *
  * @see taoItems_models_classes_ItemExporter::export()
  * @param array $options An array of options.
  * @return \common_report_Report
  * @throws ExportException
  * @throws \common_Exception
  * @throws \common_exception_Error
  * @throws \core_kernel_persistence_Exception
  * @throws PortableElementInvalidAssetException
  */
 public function export($options = array())
 {
     $report = \common_report_Report::createSuccess();
     $asApip = isset($options['apip']) && $options['apip'] === true;
     $lang = \common_session_SessionManager::getSession()->getDataLanguage();
     $basePath = $this->buildBasePath();
     if (is_null($this->getItemModel())) {
         throw new ExportException('', 'No Item Model found for item : ' . $this->getItem()->getUri());
     }
     $dataFile = (string) $this->getItemModel()->getOnePropertyValue(new core_kernel_classes_Property(TAO_ITEM_MODEL_DATAFILE_PROPERTY));
     $resolver = new ItemMediaResolver($this->getItem(), $lang);
     $replacementList = array();
     $modelsAssets = $this->getPortableElementAssets($this->getItem(), $lang);
     $service = new PortableElementService();
     $service->setServiceLocator(ServiceManager::getServiceManager());
     $portableElementsToExport = $portableAssetsToExport = [];
     foreach ($modelsAssets as $key => $portableElements) {
         /** @var  $element */
         foreach ($portableElements as $element) {
             if (!$element instanceof Element) {
                 continue;
             }
             try {
                 $object = $service->retrieve($key, $element->getTypeIdentifier());
             } catch (PortableElementException $e) {
                 $message = __('Fail to export item') . ' (' . $this->getItem()->getLabel() . '): ' . $e->getMessage();
                 return \common_report_Report::createFailure($message);
             }
             $portableElementsToExport[$element->getTypeIdentifier()] = $object;
             $files = $object->getModel()->getValidator()->getAssets($object, 'runtime');
             $baseUrl = $basePath . DIRECTORY_SEPARATOR . $object->getTypeIdentifier();
             $portableAssetsToExport[$object->getTypeIdentifier()] = [];
             foreach ($files as $url) {
                 try {
                     // Skip shared libraries into portable element
                     if (strpos($url, './') !== 0) {
                         \common_Logger::i('Shared libraries skipped : ' . $url);
                         $portableAssetsToExport[$object->getTypeIdentifier()][$url] = $url;
                         continue;
                     }
                     $stream = $service->getFileStream($object, $url);
                     $replacement = $this->copyAssetFile($stream, $baseUrl, $url, $replacementList);
                     $portableAssetToExport = preg_replace('/^(.\\/)(.*)/', $object->getTypeIdentifier() . "/\$2", $replacement);
                     $portableAssetsToExport[$object->getTypeIdentifier()][$url] = $portableAssetToExport;
                     \common_Logger::i('File copied: "' . $url . '" for portable element ' . $object->getTypeIdentifier());
                 } catch (\tao_models_classes_FileNotFoundException $e) {
                     \common_Logger::i($e->getMessage());
                     $report->setMessage('Missing resource for ' . $url);
                     $report->setType(\common_report_Report::TYPE_ERROR);
                 }
             }
         }
     }
     $assets = $this->getAssets($this->getItem(), $lang);
     foreach ($assets as $assetUrl) {
         try {
             $mediaAsset = $resolver->resolve($assetUrl);
             $mediaSource = $mediaAsset->getMediaSource();
             if (!$mediaSource instanceof HttpSource) {
                 $link = $mediaAsset->getMediaIdentifier();
                 $stream = $mediaSource->getFileStream($link);
                 $baseName = $mediaSource instanceof LocalItemSource ? $link : 'assets/' . $mediaSource->getBaseName($link);
                 $replacement = $this->copyAssetFile($stream, $basePath, $baseName, $replacementList);
                 $replacementList[$assetUrl] = $replacement;
             }
         } catch (\tao_models_classes_FileNotFoundException $e) {
             $replacementList[$assetUrl] = '';
             $report->setMessage('Missing resource for ' . $assetUrl);
             $report->setType(\common_report_Report::TYPE_ERROR);
         }
     }
     $xml = Service::singleton()->getXmlByRdfItem($this->getItem());
     $dom = new DOMDocument('1.0', 'UTF-8');
     $dom->preserveWhiteSpace = false;
     $dom->formatOutput = true;
     if ($dom->loadXML($xml) === true) {
         $xpath = new \DOMXPath($dom);
         $attributeNodes = $xpath->query('//@*');
         $portableEntryNodes = $xpath->query("//*[local-name()='entry']") ?: [];
         unset($xpath);
         foreach ($attributeNodes as $node) {
             if (isset($replacementList[$node->value])) {
                 $node->value = $replacementList[$node->value];
             }
         }
         foreach ($portableEntryNodes as $node) {
             $node->nodeValue = strtr(htmlentities($node->nodeValue, ENT_XML1), $replacementList);
         }
         $this->exportPortableAssets($dom, 'portableCustomInteraction', 'customInteractionTypeIdentifier', 'pci', $portableElementsToExport, $portableAssetsToExport);
         $this->exportPortableAssets($dom, 'portableInfoControl', 'infoControlTypeIdentifier', 'pic', $portableElementsToExport, $portableAssetsToExport);
     } else {
         throw new ExportException($this->getItem()->getLabel(), 'Unable to load XML');
     }
     $dom->preserveWhiteSpace = true;
     $dom->formatOutput = true;
     if (($content = $dom->saveXML()) === false) {
         throw new ExportException($this->getItem()->getLabel(), 'Unable to save XML');
     }
     // Possibility to delegate (if necessary) some item content post-processing to sub-classes.
     $content = $this->itemContentPostProcessing($content);
     // add xml file
     $this->getZip()->addFromString($basePath . '/' . $dataFile, $content);
     if (!$report->getMessage()) {
         $report->setMessage(__('Item ' . $this->getItem()->getLabel() . ' exported.'));
     }
     return $report;
 }
 public function sharedStimulusImportProvider()
 {
     $sampleDir = dirname(__DIR__) . '/sample/sharedStimulus/';
     return array(array($sampleDir . 'UnknowFile.zip', \common_report_Report::createFailure(__('Unable to open archive ' . $sampleDir . 'UnknowFile.zip')), false), array($sampleDir . 'missingXmlArchive.zip', \common_report_Report::createFailure('XML not found'), false), array($sampleDir . 'stimulusPackage.zip', \common_report_Report::createSuccess(__('Shared Stimulus %s successfully')), true));
 }
 /**
  * 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;
 }