/**
  * (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;
 }
 /**
  * (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;
 }
 /**
  * create a new QTI item
  * 
  * @requiresRight id WRITE
  */
 public function createItem()
 {
     if (!\tao_helpers_Request::isAjax()) {
         throw new \Exception("wrong request mode");
     }
     $clazz = new \core_kernel_classes_Resource($this->getRequestParameter('id'));
     if ($clazz->isClass()) {
         $clazz = new \core_kernel_classes_Class($clazz);
     } else {
         foreach ($clazz->getTypes() as $type) {
             // determine class from selected instance
             $clazz = $type;
             break;
         }
     }
     $service = \taoItems_models_classes_ItemsService::singleton();
     $label = $service->createUniqueLabel($clazz);
     $item = $service->createInstance($clazz, $label);
     if (!is_null($item)) {
         $service->setItemModel($item, new \core_kernel_classes_Resource(ItemModel::MODEL_URI));
         $response = array('label' => $item->getLabel(), 'uri' => $item->getUri());
     } else {
         $response = false;
     }
     $this->returnJson($response);
 }
 /**
  *
  */
 public function apply()
 {
     $cssFileData = $file = \tao_helpers_Http::getUploadedFile('content');
     $batchTool = new CssBatchTool($cssFileData['tmp_name']);
     $report = $batchTool->applyToClass(\taoItems_models_classes_ItemsService::singleton()->getRootClass(), $cssFileData['name']);
     $this->returnJson($report);
 }
 /**
  * Function returns items to export. 
  * Items that has no content (<b>QTI items</b> without <i>qti.xml</i> file or empty <b>Open Web Items</b>) will be filtered
  * @return core_kernel_classes_Resource[] An array of items.
  */
 protected function getResourcesToExport()
 {
     $resources = parent::getResourcesToExport();
     $service = taoItems_models_classes_ItemsService::singleton();
     $resources = array_filter($resources, function ($val) use($service) {
         return $service->hasItemContent($val);
     });
     return $resources;
 }
 protected function getRenderedItem($item)
 {
     $itemModel = $item->getOnePropertyValue(new core_kernel_classes_Property(TAO_ITEM_MODEL_PROPERTY));
     $impl = taoItems_models_classes_ItemsService::singleton()->getItemModelImplementation($itemModel);
     if (is_null($impl)) {
         throw new common_Exception('preview not supported for this item type ' . $itemModel->getUri());
     }
     return $impl->render($item, '');
 }
 public static function tearDownAfterClass()
 {
     \taoItems_models_classes_ItemsService::singleton()->deleteItem(self::$itemResource);
     // Unegister Metadata Injector.
     \oat\taoQtiItem\model\qti\Service::singleton()->getMetadataRegistry()->unregisterMetadataInjector('oat\\taoQtiItem\\model\\qti\\metadata\\ontology\\LomInjector');
     // Unregister Metadata Extractor.
     \oat\taoQtiItem\model\qti\Service::singleton()->getMetadataRegistry()->unregisterMetadataExtractor('oat\\taoQtiItem\\model\\qti\\metadata\\imsManifest\\ImsManifestMetadataExtractor');
     // Unregister Metadata Guardian.
     \oat\taoQtiItem\model\qti\Service::singleton()->getMetadataRegistry()->unregisterMetadataGuardian('oat\\taoQtiItem\\model\\qti\\metadata\\guardians\\LomIdentifierGuardian');
 }
 public static function tearDownAfterClass()
 {
     \taoItems_models_classes_ItemsService::singleton()->deleteItem(self::$itemResource);
     // Unregister Metadata ClassLookup.
     \oat\taoQtiItem\model\qti\Service::singleton()->getMetadataRegistry()->unregisterMetadataClassLookup('oat\\taoQtiItem\\model\\qti\\metadata\\classLookups\\LabelClassLookup');
     // Unregister Metadata Extractor.
     \oat\taoQtiItem\model\qti\Service::singleton()->getMetadataRegistry()->unregisterMetadataExtractor('oat\\taoQtiItem\\model\\qti\\metadata\\imsManifest\\ImsManifestMetadataExtractor');
     // Delete fake class
     $class = new \core_kernel_classes_Class('http://www.test.com#mytestclass');
     $class->delete(true);
 }
 /**
  * Overriden export for OWIs
  * @see taoItems_models_classes_ItemExporter::export()
  */
 public function export($options = array())
 {
     $itemService = \taoItems_models_classes_ItemsService::singleton();
     // copy local files
     $source = $itemService->getItemDirectory($this->getItem());
     $files = $source->getFlyIterator(Directory::ITERATOR_FILE | Directory::ITERATOR_RECURSIVE);
     foreach ($files as $file) {
         $relPath = ltrim($source->getRelPath($file), '/');
         $this->addFile($file->readStream(), $relPath);
     }
 }
 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());
             }
         }
     }
 }
 /**
  * Get item content tokenizer associated to $resource e.q. item model
  * If not return null
  *
  * @param core_kernel_classes_Resource $resource
  * @return null|taoItems_models_classes_itemModel
  */
 protected function getItemContentTokenizer(core_kernel_classes_Resource $resource)
 {
     $itemService = taoItems_models_classes_ItemsService::singleton();
     $model = $itemService->getItemModel($resource);
     if (!is_null($model)) {
         $impl = $itemService->getItemModelImplementation($model);
         if (!is_null($impl)) {
             if ($impl instanceof IndexableItemModel) {
                 return $impl->getItemContentTokenizer();
             }
         }
     }
     return null;
 }
 protected function getAvailableImportHandlers()
 {
     $returnValue = parent::getAvailableImportHandlers();
     $itemModelClass = new core_kernel_classes_Class(TAO_ITEM_MODEL_CLASS);
     foreach ($itemModelClass->getInstances() as $model) {
         $impl = taoItems_models_classes_ItemsService::singleton()->getItemModelImplementation($model);
         if (in_array('tao_models_classes_import_ImportProvider', class_implements($impl))) {
             foreach ($impl->getImportHandlers() as $handler) {
                 array_unshift($returnValue, $handler);
             }
         }
     }
     return $returnValue;
 }
 public function testAdd()
 {
     $itemService = \taoItems_models_classes_ItemsService::singleton();
     $item = $itemService->createInstance($itemService->getRootClass(), 'testItem');
     $source = new LocalItemSource(array('item' => $item, 'lang' => DEFAULT_LANG));
     $sampleFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'samples' . DIRECTORY_SEPARATOR . 'asset' . DIRECTORY_SEPARATOR . 'sample.css';
     $info = $source->add($sampleFile, 'example.txt', '/');
     $this->assertEquals('example.txt', $info['name']);
     $this->assertEquals('/example.txt', $info['uri']);
     $this->assertEquals('/example.txt', $info['filePath']);
     // this is only true for local item source
     $link = $info['uri'];
     $asset = new MediaAsset($source, $link);
     return $asset;
 }
 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));
     }
 }
 /**
  * Delete items, test & delivery
  *
  * @param \core_kernel_classes_Resource $delivery
  * @param $testUri
  */
 public function removeDeliveryTest(\core_kernel_classes_Resource $delivery, $testUri)
 {
     $test = new \core_kernel_classes_Resource($testUri);
     $items = $this->testService->getItems($test);
     /** @var \core_kernel_classes_Resource $item */
     foreach ($items as $item) {
         // Delete resource & files
         $this->itemService->deleteResource($item);
         $this->assertFalse($item->exists());
     }
     $this->testService->deleteContent($test);
     $this->testService->deleteResource($test);
     $this->assertFalse($test->exists());
     $this->deliveryService->deleteInstance($delivery);
     $this->assertFalse($delivery->exists());
 }
 /**
  * Get ALL QTI items within the platform.
  * 
  * The response is encoded in JSON and contains only some basic data about items (uri, label keys).
  * A 'pattern' request parameter parameter is allowed to filter results at search time.
  * A 'notempty' ('1', 'true', 'on' and 'yes' values available) request parameter is allowed to filter empty items.
  * 
  * This method will be refactored (limit, filtering, etc.) with the resource widget.
  */
 public function get()
 {
     $items = array();
     $propertyFilters = array(TAO_ITEM_MODEL_PROPERTY => TAO_ITEM_MODEL_QTI);
     $options = array('recursive' => true, 'like' => true, 'limit' => 50);
     $notEmpty = filter_var($this->getRequestParameter('notempty'), FILTER_VALIDATE_BOOLEAN);
     if (($pattern = $this->getRequestParameter('pattern')) !== null && $pattern !== '') {
         $propertyFilters[RDFS_LABEL] = $pattern;
     }
     $itemsService = taoItems_models_classes_ItemsService::singleton();
     $itemClass = $itemsService->getRootClass();
     $result = $itemClass->searchInstances($propertyFilters, $options);
     foreach ($result as $qtiItem) {
         if (!$notEmpty || $itemsService->hasItemContent($qtiItem)) {
             $items[] = array('uri' => $qtiItem->getUri(), 'label' => $qtiItem->getLabel());
         }
     }
     $this->returnJson($items);
 }
 public function testCreateQtiItem()
 {
     $url = $this->host . 'taoQtiItem/RestQtiItem/createQtiItem';
     $return = $this->curl($url, CURLOPT_POST, 'data', array(CURLOPT_POSTFIELDS => array()));
     $data = json_decode($return, true);
     $this->assertInternalType('array', $data);
     $this->assertTrue(isset($data['success']));
     $this->assertTrue($data['success']);
     $this->assertTrue(isset($data['data']));
     $itemUri = $data['data'];
     $this->assertInternalType('string', $itemUri);
     $item = $this->getResource($itemUri);
     $this->assertTrue($item->exists());
     $itemService = \taoItems_models_classes_ItemsService::singleton();
     $model = $itemService->getItemModel($item);
     $this->assertNotNull($model);
     $this->assertEquals(ItemModel::MODEL_URI, $itemService->getItemModel($item)->getUri());
     $this->assertTrue($itemService->deleteResource($item));
     $this->assertFalse($item->exists());
 }
 protected function convertQtiItem(core_kernel_classes_Resource $item)
 {
     $itemService = taoItems_models_classes_ItemsService::singleton();
     $itemContentProp = new core_kernel_classes_Property(TAO_ITEM_CONTENT_PROPERTY);
     $usedLanguages = $item->getUsedLanguages($itemContentProp);
     foreach ($usedLanguages as $lang) {
         $this->out('language:' . $lang);
         $xmlString = $itemService->getItemContent($item, $lang);
         if (empty($xmlString)) {
             $this->out('no qti xml found');
         } else {
             $qti = $this->convertQtiFromV2p0ToV2p1($xmlString);
             if (empty($qti)) {
                 $this->out('fail');
             } else {
                 $this->out('done');
             }
         }
     }
 }
 public function testResourceManager()
 {
     $itemClass = taoItems_models_classes_ItemsService::singleton()->getRootClass();
     $report = ImportService::singleton()->importQTIPACKFile(dirname(__FILE__) . '/samples/package/QTI/package.zip', $itemClass);
     $items = array();
     foreach ($report as $itemReport) {
         $data = $itemReport->getData();
         if (!is_null($data)) {
             $items[] = $data;
         }
     }
     $this->assertEquals(1, count($items));
     $item = current($items);
     $this->assertIsA($item, 'core_kernel_classes_Resource');
     $this->assertTrue($item->exists());
     $rm = new LocalItemSource(array('item' => $item, 'lang' => DEFAULT_LANG));
     $data = $rm->getDirectory();
     $this->assertTrue(is_array($data));
     $this->assertTrue(isset($data['path']));
     $this->assertEquals('/', $data['path']);
     $this->assertTrue(isset($data['children']));
     $children = $data['children'];
     $this->assertEquals(2, count($children));
     $file = null;
     $dir = null;
     foreach ($children as $child) {
         if (isset($child['path'])) {
             $dir = $child;
         }
         if (isset($child['name'])) {
             $file = $child;
         }
     }
     $this->assertEquals("qti.xml", $file['name']);
     $this->assertTrue(strpos($file['mime'], '/xml') !== false);
     //can be 'application/xml' or 'text/xml'
     $this->assertTrue($file['size'] > 0);
     $this->assertEquals("/images/", $dir['path']);
     taoItems_models_classes_ItemsService::singleton()->deleteItem($item);
     $this->assertFalse($item->exists());
 }
 /**
  * tests initialization
  * load qti service
  */
 public function setUp()
 {
     TaoPhpUnitTestRunner::initTest();
     \common_ext_ExtensionsManager::singleton()->getExtensionById('taoItems');
     $itemTopClass = new \core_kernel_classes_Class('http://www.tao.lu/Ontologies/TAOItem.rdf#Item');
     $this->itemClass = $itemTopClass->createSubClass('style service unit test', 'create for unit test ' . time());
     $itemService = \taoItems_models_classes_ItemsService::singleton();
     $qtiItemModel = new \core_kernel_classes_Resource(ItemModel::MODEL_URI);
     $itemA = $this->itemClass->createInstance('itemA');
     $itemService->setItemModel($itemA, $qtiItemModel);
     $itemService->setItemContent($itemA, file_get_contents(dirname(__FILE__) . '/samples/itemA.xml'));
     $this->items[] = $itemA;
     $itemB = $this->itemClass->createInstance('itemB');
     $itemService->setItemModel($itemB, $qtiItemModel);
     $itemService->setItemContent($itemB, file_get_contents(dirname(__FILE__) . '/samples/itemB.xml'));
     $this->items[] = $itemB;
     $itemC = $this->itemClass->createInstance('itemC');
     $itemService->setItemModel($itemC, $qtiItemModel);
     $itemService->setItemContent($itemC, file_get_contents(dirname(__FILE__) . '/samples/itemC.xml'));
     $this->items[] = $itemC;
 }
 /**
  * deploys the item into the given absolute directory 
  * 
  * @param core_kernel_classes_Resource $item
  * @param string $languageCode
  * @param string $compiledDirectory
  * @return common_report_Report
  */
 protected function deployItem(core_kernel_classes_Resource $item, $languageCode, $compiledDirectory)
 {
     $itemService = taoItems_models_classes_ItemsService::singleton();
     // copy local files
     $source = $itemService->getItemFolder($item, $languageCode);
     $success = taoItems_helpers_Deployment::copyResources($source, $compiledDirectory, array('index.html'));
     if (!$success) {
         return $this->fail(__('Unable to copy resources for language %s', $languageCode));
     }
     // render item
     $xhtml = $itemService->render($item, $languageCode);
     // retrieve external resources
     $subReport = taoItems_helpers_Deployment::retrieveExternalResources($xhtml, $compiledDirectory);
     if ($subReport->getType() == common_report_Report::TYPE_SUCCESS) {
         $xhtml = $subReport->getData();
         // write index.html
         file_put_contents($compiledDirectory . 'index.html', $xhtml);
         return new common_report_Report(common_report_Report::TYPE_SUCCESS, __('Published "%1$s" in language "%2$s"', $item->getLabel(), $languageCode));
     } else {
         return $subReport;
     }
 }
 public function delete($resource)
 {
     taoItems_models_classes_ItemsService::singleton()->deleteItem(new core_kernel_classes_Resource($resource));
     //parent::delete($resource)
     return true;
 }
 /**
  * @depends testInstantiateClass
  * @param \core_kernel_classes_Resource $instance
  */
 public function testDeleteInstance($instance)
 {
     $this->assertTrue($this->itemsService->deleteItem($instance));
     $this->assertFalse($instance->exists());
 }
 /**
  * Obtains a reference on the TAO Item Service.
  *
  * @return taoItems_models_classes_ItemsService A TAO Item Service.
  */
 protected function getItemService()
 {
     return taoItems_models_classes_ItemsService::singleton();
 }
 /**
  * 
  * @param string $currentVersion
  * @return string $versionUpdatedTo
  */
 public function update($initialVersion)
 {
     $currentVersion = $initialVersion;
     //migrate from 2.6 to 2.6.1
     if ($currentVersion == '2.6') {
         $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'indexation_2_6_1.rdf';
         $adapter = new tao_helpers_data_GenerisAdapterRdf();
         if ($adapter->import($file)) {
             $currentVersion = '2.6.1';
         } else {
             common_Logger::w('Import failed for ' . $file);
         }
     }
     if ($currentVersion == '2.6.1') {
         // double check
         $index = new core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAOItem.rdf#ItemContentIndex');
         $default = $index->getPropertyValues(new core_kernel_classes_Property('http://www.tao.lu/Ontologies/TAO.rdf#IndexDefaultSearch'));
         if (count($default) == 0) {
             //no default search set, import
             $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'indexation_2_6_2.rdf';
             $adapter = new tao_helpers_data_GenerisAdapterRdf();
             if ($adapter->import($file)) {
                 $currentVersion = '2.6.2';
             } else {
                 common_Logger::w('Import failed for ' . $file);
             }
         } else {
             common_Logger::w('Defautl Search already set');
             $currentVersion = '2.6.2';
         }
     }
     if ($currentVersion == '2.6.2') {
         OntologyUpdater::correctModelId(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'indexation_2_6_1.rdf');
         OntologyUpdater::correctModelId(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'indexation_2_6_2.rdf');
         $currentVersion = '2.6.3';
     }
     if ($currentVersion == '2.6.3') {
         // update user roles
         $class = new core_kernel_classes_Class(CLASS_TAO_USER);
         $itemManagers = $class->searchInstances(array(PROPERTY_USER_ROLES => 'http://www.tao.lu/Ontologies/TAOItem.rdf#ItemsManagerRole'), array('recursive' => true, 'like' => false));
         foreach ($itemManagers as $user) {
             $user->setPropertyValue(new core_kernel_classes_Property(PROPERTY_USER_ROLES), ItemAuthorRole::INSTANCE_URI);
         }
         $currentVersion = '2.6.4';
     }
     if ($currentVersion == '2.6.4') {
         $currentVersion = '2.6.5';
     }
     if ($currentVersion == '2.6.5') {
         $currentVersion = '2.7.0';
     }
     if ($currentVersion == '2.7.0') {
         $currentVersion = '2.8';
     }
     // fix itemModelLabelProp
     if ($currentVersion == '2.8') {
         $fakeProperty = new core_kernel_classes_Property('itemModelLabel');
         $iterator = new core_kernel_classes_ResourceIterator(array(taoItems_models_classes_ItemsService::singleton()->getRootClass()));
         foreach ($iterator as $resource) {
             $resource->removePropertyValues($fakeProperty);
         }
         $currentVersion = '2.8.1';
     }
     return $currentVersion;
 }
 protected function getInstances($classToExport)
 {
     $instances = array();
     $itemService = \taoItems_models_classes_ItemsService::singleton();
     foreach ($classToExport->getInstances(true) as $item) {
         if ($itemService->hasItemModel($item, array(ItemModel::MODEL_URI))) {
             $instances[] = $item;
         }
     }
     return $instances;
 }
 private function compileItem(core_kernel_classes_Resource $item, $directory)
 {
     $compiler = taoItems_models_classes_ItemsService::singleton()->getCompiler($item);
     $service = $compiler->compile($directory);
     return $service->toOntology();
 }
 /**
  * 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();
     // Prepare Metadata mechanisms.
     $metadataMapping = oat\taoQtiItem\model\qti\Service::singleton()->getMetadataRegistry()->getMapping();
     $metadataInjectors = array();
     $metadataGuardians = array();
     $metadataClassLookups = array();
     $metadataValues = array();
     $domManifest = new DOMDocument('1.0', 'UTF-8');
     $domManifest->load($folder . 'imsmanifest.xml');
     foreach ($metadataMapping['injectors'] as $injector) {
         $metadataInjectors[] = new $injector();
     }
     foreach ($metadataMapping['guardians'] as $guardian) {
         $metadataGuardians[] = new $guardian();
     }
     foreach ($metadataMapping['classLookups'] as $classLookup) {
         $metadataClassLookups[] = new $classLookup();
     }
     foreach ($metadataMapping['extractors'] as $extractor) {
         $metadataExtractor = new $extractor();
         $metadataValues = array_merge($metadataValues, $metadataExtractor->extract($domManifest));
     }
     // 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['items']) > 0) {
                 foreach ($dependencies['items'] as $assessmentItemRefId => $qtiDependency) {
                     if ($qtiDependency !== false) {
                         if (Resource::isAssessmentItem($qtiDependency->getType())) {
                             $resourceIdentifier = $qtiDependency->getIdentifier();
                             // Check if the item is already stored in the bank.
                             foreach ($metadataGuardians as $guardian) {
                                 if (isset($metadataValues[$resourceIdentifier]) === true) {
                                     if (($guard = $guardian->guard($metadataValues[$resourceIdentifier])) !== false) {
                                         common_Logger::i("Item with identifier '{$resourceIdentifier}' already in Item Bank.");
                                         $msg = __('The IMS QTI Item referenced as "%s" in the IMS Manifest file was already stored in the Item Bank.', $resourceIdentifier);
                                         $report->add(common_report_Report::createInfo($msg, $guard));
                                         $reportCtx->items[$assessmentItemRefId] = $guard;
                                         // Simply do not import again.
                                         continue 2;
                                     }
                                 }
                             }
                             // Determine target class from metadata, if possible.
                             // This is applied to items, not for test definitions.
                             // The test definitions' target class will not be affected
                             // by class lookups.
                             $lookupTargetClass = false;
                             foreach ($metadataClassLookups as $classLookup) {
                                 if (isset($metadataValues[$resourceIdentifier]) === true) {
                                     if (($lookupTargetClass = $classLookup->lookup($metadataValues[$resourceIdentifier])) !== false) {
                                         break;
                                     }
                                 }
                             }
                             $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) {
                                 $isApip = $qtiDependency->getType() === 'imsqti_apipitem_xmlv2p1';
                                 $itemReport = $itemImportService->importQtiItem($folder, $qtiDependency, $lookupTargetClass !== false ? $lookupTargetClass : $targetClass, $isApip, $dependencies['dependencies']);
                                 $rdfItem = $itemReport->getData();
                                 if ($rdfItem) {
                                     $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());
                         // 4. if $targetClass does not contain any instances (because everything resolved by class lookups),
                         // Just delete it.
                         if ($targetClass->countInstances() == 0) {
                             $targetClass->delete();
                         }
                     }
                 } 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;
 }
<?php

/**
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; under version 2
 * of the License (non-upgradable).
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * Copyright (c) 2016 (original work) Open Assessment Technologies SA ;
 */
/**
 * @author Jean-Sébastien Conan <*****@*****.**>
 */
require_once dirname(__FILE__) . '/../../tao/includes/raw_start.php';
common_ext_ExtensionsManager::singleton()->getExtensionById('taoQtiItem');
$fs = taoItems_models_classes_ItemsService::singleton()->getDefaultFileSource();
$itemUpdater = new \oat\taoQtiItem\model\update\ItemFixGhostResponse($fs->getPath());
$fixed = $itemUpdater->update(true);
echo "Fixed " . count($fixed) . " items\n";
 protected function getSubCompilerClass(core_kernel_classes_Resource $resource)
 {
     return taoItems_models_classes_ItemsService::singleton()->getCompilerClass($resource);
 }