/** * (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; }
/** * Import file entry point by using $this->service * Check POST method & get valid uploaded file */ public function import() { try { // Check if it's post method if ($this->getRequestMethod() != Request::HTTP_POST) { throw new \common_exception_NotImplemented('Only post method is accepted to import Qti package.'); } // Get valid package parameter $package = $this->getUploadedPackage(); // Call service to import package \helpers_TimeOutHelper::setTimeOutLimit(\helpers_TimeOutHelper::LONG); $report = ImportService::singleton()->importQTIPACKFile($package, $this->getDestinationClass()); \helpers_TimeOutHelper::reset(); \tao_helpers_File::remove($package); if ($report->getType() !== \common_report_Report::TYPE_SUCCESS) { $this->returnFailure(new \common_Exception(__("An unexpected error occured during the import of the IMS QTI Item Package."))); } else { $itemIds = []; /** @var \common_report_Report $subReport */ foreach ($report as $subReport) { $itemIds[] = $subReport->getData()->getUri(); } $this->returnSuccess(array('items' => $itemIds)); } } catch (ExtractException $e) { $this->returnFailure(new \common_Exception(__('The ZIP archive containing the IMS QTI Item cannot be extracted.'))); } catch (ParsingException $e) { $this->returnFailure(new \common_Exception(__('The ZIP archive does not contain an imsmanifest.xml file or is an invalid ZIP archive.'))); } catch (\Exception $e) { $this->returnFailure($e); } }
protected static function install($extension, $installData) { $importLocalData = isset($installData['import_local']) && $installData['import_local'] == true; $extinstaller = static::getInstaller($extension, $importLocalData); helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::LONG); $extinstaller->install(); helpers_TimeOutHelper::reset(); }
/** * * @author Rashid Mumtaz & Absar - PCG Team - {absar.gilani6@gmail.com & rashid.mumtaz372@gmail.com} * @param array $propertiesValues * @return common_report_Report */ public function importQtiTest($uploadedFile, $class = null) { //test versioning try { //The zip extraction is a long process that can exceed the 30s timeout helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::LONG); $class = is_null($class) ? new core_kernel_classes_Class(TAO_TEST_CLASS) : $class; $report = taoQtiTest_models_classes_QtiTestService::singleton()->importMultipleTests($class, $uploadedFile); helpers_TimeOutHelper::reset(); return $report; } catch (common_exception_UserReadableException $e) { return new common_report_Report(common_report_Report::TYPE_ERROR, __($e->getUserMessage())); } }
/** * @param \core_kernel_classes_Resource $instance * @param \tao_helpers_form_Form $form * @return \common_report_Report */ public function edit($instance, $form) { \helpers_TimeOutHelper::setTimeOutLimit(\helpers_TimeOutHelper::LONG); try { $fileInfo = $form->getValue('source'); $xmlFile = $this->getSharedStimulusFile($fileInfo['uploaded_file']); // throws an exception of invalid SharedStimulusImporter::isValidSharedStimulus($xmlFile); $embeddedFile = $this->embedAssets($xmlFile); $report = $this->replaceSharedStimulus($instance, \tao_helpers_Uri::decode($form->getValue('lang')), $embeddedFile); } catch (\Exception $e) { $report = \common_report_Report::createFailure($e->getMessage()); } \helpers_TimeOutHelper::reset(); return $report; }
/** * (non-PHPdoc) * @see tao_models_classes_import_ImportHandler::import() */ public function import($class, $form) { try { $fileInfo = $form->getValue('source'); if (isset($fileInfo['uploaded_file'])) { $uploadedFile = $fileInfo['uploaded_file']; // The zip extraction is a long process that can exceed the 30s timeout helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::LONG); $report = taoQtiTest_models_classes_QtiTestService::singleton()->importMultipleTests($class, $uploadedFile); helpers_TimeOutHelper::reset(); tao_helpers_File::remove($uploadedFile); } else { throw new common_exception_Error('No source file for import'); } return $report; } catch (Exception $e) { return common_report_Report::createFailure($e->getMessage()); } }
public function initProcessExecution($posted) { //set_time_limit(200); helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::LONG); $processExecutionService = wfEngine_models_classes_ProcessExecutionService::singleton(); $activityExecutionService = wfEngine_models_classes_ActivityExecutionService::singleton(); $processDefinitionUri = urldecode($posted['executionOf']); $processDefinition = new core_kernel_classes_Resource($processDefinitionUri); $processExecName = $posted["variables"][RDFS_LABEL]; $processExecComment = 'Created in Processes server on ' . date(DATE_ISO8601); $processVariables = $posted["variables"]; $newProcessExecution = $processExecutionService->createProcessExecution($processDefinition, $processExecName, $processExecComment, $processVariables); //create nonce to initial activity executions: foreach ($processExecutionService->getCurrentActivityExecutions($newProcessExecution) as $initialActivityExecution) { $activityExecutionService->createNonce($initialActivityExecution); } helpers_TimeOutHelper::reset(); $param = array('processUri' => urlencode($newProcessExecution->getUri())); $this->redirect(tao_helpers_Uri::url('index', 'ProcessBrowser', null, $param)); }
public function run() { //set_time_limit(200); helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::LONG); $processExecutionService = wfEngine_models_classes_ProcessExecutionService::singleton(); $activityExecutionService = wfEngine_models_classes_ActivityExecutionService::singleton(); $processDefinitionUri = $this->getRequestParameter('processDefinition'); $processDefinition = new core_kernel_classes_Resource($processDefinitionUri); if (!$this->hasRequestParameter('serviceCallId')) { throw new common_exception_Error('No serviceCallId on service call'); } $serviceService = tao_models_classes_service_StateStorage::singleton(); $userUri = common_session_SessionManager::getSession()->getUserUri(); $processExecutionUri = is_null($userUri) ? null : $serviceService->get($userUri, $this->getRequestParameter('serviceCallId')); if (is_null($processExecutionUri)) { $processExecName = $processDefinition->getLabel(); $processExecComment = 'Created in Processes server on ' . date(DATE_ISO8601); if (isset($_REQUEST['processVariables']) && !empty($_REQUEST['processVariables'])) { $processVariables = json_decode($_REQUEST['processVariables'], true); $processVariables = is_array($processVariables) ? $processVariables : array(); } else { // none provided $processVariables = array(); } $newProcessExecution = $processExecutionService->createProcessExecution($processDefinition, $processExecName, $processExecComment, $processVariables); $processExecutionUri = $newProcessExecution->getUri(); $serviceService->set($userUri, $this->getRequestParameter('serviceCallId'), $processExecutionUri); } $processExecution = new core_kernel_classes_Resource($processExecutionUri); //create nonce to initial activity executions: foreach ($processExecutionService->getCurrentActivityExecutions($processExecution) as $initialActivityExecution) { $activityExecutionService->createNonce($initialActivityExecution); } helpers_TimeOutHelper::reset(); $param = array('processUri' => urlencode($processExecution->getUri()), 'standalone' => 'true'); $this->redirect(tao_helpers_Uri::url('index', null, null, $param)); }
/** * Compile the given $test into PHP source code for maximum performance. The file will be stored * into PRIVATE_DIRECTORY/compact-test.php. * * @param AssessmentTest $test */ protected function compileTest(AssessmentTest $test) { // Compiling a test may require extra processing time. helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::MEDIUM); $phpCompiledDoc = new PhpDocument('2.1', $test); $data = $phpCompiledDoc->saveToString(); $this->getPrivateDirectory()->write(TAOQTITEST_COMPILED_FILENAME, $data); common_Logger::d("QTI-PHP Test Compilation file saved to stream."); }
/** * Retrieve a file from a given $url and copy it to its final $destination. * * @param string $url The URL to be dereferenced. * @param string $destination The destination of the retrieved file, on the file system. * @return boolean|string false If an error occurs during the retrieval/copy process, or the final destination name if it succeeds. */ public static function retrieveFile($url, $destination) { $fileName = basename($url); //check file name compatibility: //e.g. if a file with a common name (e.g. car.jpg, house.png, sound.mp3) already exists in the destination folder while (file_exists($destination . $fileName)) { $lastDot = strrpos($fileName, '.'); $fileName = substr($fileName, 0, $lastDot) . '_' . substr($fileName, $lastDot); } // Since the file has not been downloaded yet, start downloading it using cUrl // Only if the resource is external, else we copy it if (!preg_match('@^' . ROOT_URL . '@', $url)) { common_Logger::d('Downloading ' . $url); helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::NO_TIMEOUT); $fp = fopen($destination . $fileName, 'w+'); $curlHandler = curl_init(); curl_setopt($curlHandler, CURLOPT_URL, $url); curl_setopt($curlHandler, CURLOPT_FILE, $fp); curl_setopt($curlHandler, CURLOPT_TIMEOUT, 50); curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, true); //if there is an http auth on the local domain, it's mandatory to auth with curl if (USE_HTTP_AUTH) { $addAuth = false; $domains = array('localhost', '127.0.0.1', ROOT_URL); foreach ($domains as $domain) { if (preg_match("/" . preg_quote($domain, '/') . "/", $url)) { $addAuth = true; } } if ($addAuth) { curl_setopt($curlHandler, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curlHandler, CURLOPT_USERPWD, USE_HTTP_USER . ":" . USE_HTTP_PASS); } } curl_exec($curlHandler); $httpCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); $success = $httpCode == 200; curl_close($curlHandler); fclose($fp); helpers_TimeOutHelper::reset(); } else { $path = tao_helpers_File::getPathFromUrl($url); common_Logger::d('Copying ' . $path); $success = helpers_File::copy($path, $destination . $fileName); } if ($success == false) { common_Logger::w('Unable to retrieve ' . $url); return false; } else { return $destination . $fileName; } }
/** * Imports the currently loaded CsvFile into the destination Class. * The map should be set in the options before executing it. * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @param string $source * @param core_kernel_classes_Class $destination * @return common_report_Report */ public function import($source, core_kernel_classes_Class $destination = null) { if (!isset($this->options['map'])) { throw new BadFunctionCallException("import map not set"); } if (is_null($destination)) { throw new InvalidArgumentException("{$destination} must be a valid core_kernel_classes_Class"); } $csvData = $this->load($source); $createdResources = 0; $toImport = $csvData->count(); $rangeProperty = new core_kernel_classes_Property(RDFS_RANGE); $report = new common_report_Report(common_report_Report::TYPE_ERROR, __('Data not imported. All records are invalid.')); for ($rowIterator = 0; $rowIterator < $csvData->count(); $rowIterator++) { helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::SHORT); common_Logger::d("CSV - Importing CSV row {$rowIterator}."); $resource = null; $csvRow = $csvData->getRow($rowIterator); try { // default values $evaluatedData = $this->options['staticMap']; // validate csv values foreach ($this->options['map'] as $propUri => $csvColumn) { $this->validate($destination, $propUri, $csvRow, $csvColumn); } // evaluate csv values foreach ($this->options['map'] as $propUri => $csvColumn) { if ($csvColumn != 'csv_null' && $csvColumn != 'csv_select') { // process value if (isset($csvRow[$csvColumn]) && !is_null($csvRow[$csvColumn])) { $property = new core_kernel_classes_Property($propUri); $evaluatedData[$propUri] = $this->evaluateValues($csvColumn, $property, $csvRow[$csvColumn]); } } } // create resource $resource = $destination->createInstanceWithProperties($evaluatedData); // Apply 'resourceImported' callbacks. foreach ($this->resourceImported as $callback) { $callback($resource); } $report->add(new common_report_Report(common_report_Report::TYPE_SUCCESS, __('Imported resource "%s"', $resource->getLabel()), $resource)); $createdResources++; } catch (ValidationException $valExc) { $failure = common_report_Report::createFailure(__('Row %s', $rowIterator + 1) . ' ' . $valExc->getProperty()->getLabel() . ': ' . $valExc->getUserMessage() . ' "' . $valExc->getValue() . '"'); $report->add($failure); } helpers_TimeOutHelper::reset(); } $this->addOption('to_import', $toImport); $this->addOption('imported', $createdResources); if ($createdResources == $toImport) { $report->setType(common_report_Report::TYPE_SUCCESS); $report->setMessage(__('Imported %d resources', $toImport)); } elseif ($createdResources > 0) { $report->setType(common_report_Report::TYPE_WARNING); $report->setMessage(__('Imported %1$d/%2$d. Some records are invalid.', $createdResources, $toImport)); } return $report; }
/** * Calling this method will transfer all instances of $class from the statements table * to specific optimized relational tables. * * During optimization, the current user has all privileges on the persistent memory. At * the end of the process, the old privileges will be set back. * * The $options array can contain the following key => values (all booleans): * * - recursive: compile the target class and its subclasses (default: false). * - append: append data to the existing optimized table if it already exists (default: false). * - rmSources: remove the triples in the statement table after transfer (default: true). * * @access public * @author Bertrand Chevrier, <*****@*****.**> * @param \core_kernel_classes_Class class * @param array options * @return boolean Will return true if it succeeds, false otherwise. */ public function hardify(\core_kernel_classes_Class $class, $options = array()) { $returnValue = (bool) false; $oldUpdatableModels = core_kernel_persistence_smoothsql_SmoothModel::getUpdatableModelIds(); try { // Give access to all models during hardification. core_kernel_persistence_smoothsql_SmoothModel::forceUpdatableModelIds(self::getAllModelIds()); $classLabel = $class->getLabel(); \common_Logger::i("Hardifying class {$classLabel}", array("GENERIS")); if (defined("DEBUG_PERSISTENCE") && DEBUG_PERSISTENCE) { if (in_array($class->getUri(), self::$debug_tables)) { return; } \common_Logger::d('hardify ' . $class->getUri()); self::$debug_tables[] = $class->getUri(); $countStatement = $this->countStatements(); } if (in_array($class->getUri(), self::$blackList)) { return $returnValue; } // ENTER IN SMOOTH SQL MODE PersistenceProxy::forceMode(PERSISTENCE_SMOOTH); //recursive will hardify the class and it's subclasses in the same table! isset($options['recursive']) ? $recursive = $options['recursive'] : ($recursive = false); //createForeigns will hardify the class that are range of the properties isset($options['createForeigns']) ? $createForeigns = $options['createForeigns'] : ($createForeigns = false); //check if we append the data in case the hard table exists or truncate the table and add the new rows isset($options['append']) ? $append = $options['append'] : ($append = false); //if true, the instances of the class will be removed from the statements table! isset($options['rmSources']) ? $rmSources = (bool) $options['rmSources'] : ($rmSources = false); //if defined, we took all the properties of the class and it's parents till the topclass isset($options['topclass']) ? $topclass = $options['topclass'] : ($topclass = new \core_kernel_classes_Class(RDFS_RESOURCE)); //if defined, compile the additional properties isset($options['additionalProperties']) ? $additionalProperties = $options['additionalProperties'] : ($additionalProperties = array()); //if defined, reference the additional class to the table isset($options['referencesAllTypes']) ? $referencesAllTypes = $options['referencesAllTypes'] : ($referencesAllTypes = false); $tableName = '_' . Utils::getShortName($class); $myTableMgr = new TableManager($tableName); $referencer = ResourceReferencer::singleton(); //get the table columns from the class properties $columns = array(); $ps = new PropertySwitcher($class); $properties = $ps->getProperties($additionalProperties); $columns = $ps->getTableColumns($additionalProperties, self::$blackList); //init the count value in hardened classes: if (isset($this->hardenedClasses[$class->getUri()])) { PersistenceProxy::restoreImplementation(); return true; //already being compiled } else { $this->hardenedClasses[$class->getUri()] = 0; } if (!$append || $append && !$myTableMgr->exists()) { //create the table if ($myTableMgr->exists()) { $myTableMgr->remove(); } $myTableMgr->create($columns); //reference the class $referencer->referenceClass($class, array("topclass" => $topclass, "additionalProperties" => $additionalProperties)); if ($referencesAllTypes) { $referencer->referenceInstanceTypes($class); } } //insert the resources $startIndex = 0; $instancePackSize = 100; $instances = $class->getInstances(false, array('offset' => $startIndex, 'limit' => $instancePackSize)); $count = count($instances); $notDeletedInstances = array(); do { //reset timeout: //set_time_limit(30); \helpers_TimeOutHelper::setTimeOutLimit(\helpers_TimeOutHelper::MEDIUM); $rows = array(); foreach ($instances as $index => $resource) { if ($referencer->isResourceReferenced($resource)) { PersistenceProxy::forceMode(PERSISTENCE_HARD); $resource->delete(); PersistenceProxy::restoreImplementation(); } $row = array('uri' => $resource->getUri()); foreach ($properties as $property) { $propValue = $resource->getOnePropertyValue($property); $row[Utils::getShortName($property)] = $propValue; } $rows[] = $row; } $rowMgr = new RowManager($tableName, $columns); $rowMgr->insertRows($rows); foreach ($instances as $resource) { $referencer->referenceResource($resource, $tableName, null, true); if ($rmSources) { //remove exported resources in smooth sql, if required: // Be carefull, the resource can still exist even if // delete returns true. Indeed, modelIds can be mixed between // multiple models and only a part of the triples that consitute // the resource might have been deleted. if (!$resource->delete() || $resource->exists()) { //@TODO : modified resource::delete() because resource not in local modelId cannot be deleted $notDeletedInstances[] = $resource->getUri(); $startIndex++; } } } if (!$rmSources) { //increment start index only if not removed $startIndex += $instancePackSize; } //record hardened instances number if (isset($this->hardenedClasses[$class->getUri()])) { $this->hardenedClasses[$class->getUri()] += $count; } else { $this->hardenedClasses[$class->getUri()] = $count; } //update instance array and count value $instances = $class->getInstances(false, array('offset' => $startIndex, 'limit' => $instancePackSize)); foreach ($notDeletedInstances as $uri) { unset($instances[$uri]); } $count = count($instances); \helpers_TimeOutHelper::reset(); } while ($count > 0); $returnValue = true; // Treat subclasses of the current class if ($recursive) { foreach ($class->getSubClasses(true) as $subClass) { $returnValue = $this->hardify($subClass, array_merge($options, array('recursive' => false, 'append' => true))); } } //reset cache: $referencer->clearCaches(); // EXIT SMOOTH SQL MODE PersistenceProxy::restoreImplementation(); if (defined("DEBUG_PERSISTENCE") && DEBUG_PERSISTENCE) { $this->unhardify($class, array_merge($options, array('recursive' => false, 'removeForeigns' => false))); \common_Logger::d('unhardened result statements ' . $this->countStatements() . ' / ' . $countStatement); } // Give the normal rights on models to the session. core_kernel_persistence_smoothsql_SmoothModel::forceUpdatableModelIds($oldUpdatableModels); } catch (Exception $e) { \common_Logger::e('An error occured during hardification: ' . $e->getMessage()); core_kernel_persistence_smoothsql_SmoothModel::forceUpdatableModelIds($oldUpdatableModels); } return (bool) $returnValue; }
/** * inserts the datamodels * specified in the Manifest * * @access protected * @author Jerome Bogaerts, <*****@*****.**> * @return void */ protected function installOntology() { helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::MEDIUM); $rdf = ModelManager::getModel()->getRdfInterface(); foreach ($this->getExtensionModel() as $triple) { $rdf->add($triple); } helpers_TimeOutHelper::reset(); }
/** * Short description of method validate * * @access public * @author Bertrand Chevrier, <*****@*****.**> * @param string schema * @return boolean */ public function validate($schema = '') { //You know sometimes you think you have enough time, but it is not always true ... //(timeout in hudson with the generis-hard test suite) helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::MEDIUM); $forced = $this->valid; $this->valid = true; try { switch ($this->sourceType) { case self::SOURCE_FILE: //check file if (!file_exists($this->source)) { throw new Exception("File {$this->source} not found."); } if (!is_readable($this->source)) { throw new Exception("Unable to read file {$this->source}."); } if (!preg_match("/\\.{$this->fileExtension}\$/", basename($this->source))) { throw new Exception("Wrong file extension in " . basename($this->source) . ", {$this->fileExtension} extension is expected"); } if (!tao_helpers_File::securityCheck($this->source)) { throw new Exception("{$this->source} seems to contain some security issues"); } break; case self::SOURCE_URL: //only same domain if (!preg_match("/^" . preg_quote(BASE_URL, '/') . "/", $this->source)) { throw new Exception("The given uri must be in the domain {$_SERVER['HTTP_HOST']}"); } break; } } catch (Exception $e) { if ($forced) { throw $e; } else { $this->addError($e); } } if ($this->valid && !$forced) { //valida can be true if forceValidation has been called $this->valid = false; try { libxml_use_internal_errors(true); $dom = new DomDocument(); $loadResult = false; switch ($this->sourceType) { case self::SOURCE_FILE: $loadResult = $dom->load($this->source); break; case self::SOURCE_URL: $xmlContent = tao_helpers_Request::load($this->source, true); $loadResult = $dom->loadXML($xmlContent); break; case self::SOURCE_STRING: $loadResult = $dom->loadXML($this->source); break; } if ($loadResult) { if (!empty($schema)) { $this->valid = $dom->schemaValidate($schema); } else { $this->valid = true; //only well-formed } } if (!$this->valid) { $this->addErrors(libxml_get_errors()); } libxml_clear_errors(); } catch (DOMException $de) { $this->addError($de); } } $returnValue = $this->valid; helpers_TimeOutHelper::reset(); return (bool) $returnValue; }
/** * Short description of method validate * * @access public * @author Bertrand Chevrier, <*****@*****.**> * @param string schema * @return boolean */ public function validate($schema = '') { //You know sometimes you think you have enough time, but it is not always true ... //(timeout in hudson with the generis-hard test suite) helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::MEDIUM); $content = $this->getContent(); if (!empty($content)) { try { libxml_use_internal_errors(true); $dom = new DomDocument(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; $this->valid = $dom->loadXML($content); if ($this->valid && !empty($schema)) { $this->valid = $dom->schemaValidate($schema); } if (!$this->valid) { $this->addErrors(libxml_get_errors()); } libxml_clear_errors(); } catch (DOMException $de) { $this->addError($de); } } helpers_TimeOutHelper::reset(); return (bool) $this->valid; }
/** * Imports the currently loaded CsvFile into the destination Class. * The map should be set in the options before executing it. * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @param string $source * @param core_kernel_classes_Class $destination * @return common_report_Report */ public function import($source, core_kernel_classes_Class $destination = null) { if (!isset($this->options['map'])) { throw new BadFunctionCallException("import map not set"); } if (is_null($destination)) { throw new InvalidArgumentException("{$destination} must be a valid core_kernel_classes_Class"); } $csvData = $this->load($source); $createdResources = 0; $rangeProperty = new core_kernel_classes_Property(RDFS_RANGE); for ($rowIterator = 0; $rowIterator < $csvData->count(); $rowIterator++) { helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::SHORT); common_Logger::d("CSV - Importing CSV row {$rowIterator}."); $resource = null; $csvRow = $csvData->getRow($rowIterator); //create the instance with the label defined in the map $label = $this->options['map'][RDFS_LABEL]; if ($label != 'csv_select' && $label != 'csv_null') { if (isset($csvRow[$label])) { $resource = $destination->createInstance($csvRow[$label]); common_Logger::t("CSV - Resource creation with label"); } } if (is_null($resource)) { $resource = $destination->createInstance(); common_Logger::t("CSV - Resource creation without label"); } if ($resource instanceof core_kernel_classes_Resource) { common_Logger::t("CSV - Resource successfully created"); //import the value of each column into the property defined in the map foreach ($this->options['map'] as $propUri => $csvColumn) { if ($propUri != RDFS_LABEL) { // Already set at resource instantiation $targetProperty = new core_kernel_classes_Property($propUri); $ranges = $targetProperty->getPropertyValues($rangeProperty); if (count($ranges) > 0) { // @todo support multi-valued ranges in CSV import. common_Logger::t("CSV - Target property has " . $ranges[0] . " for range"); $range = new core_kernel_classes_Resource($ranges[0]); } else { common_Logger::t("CSV - Target property has no range"); $range = null; } //stop future action if validation was not passed $valid = $this->validate($destination, $propUri, $csvRow, $csvColumn); if (!$valid) { break; } if ($range == null || $range->getUri() == RDFS_LITERAL) { // Deal with the column value as a literal. common_Logger::t("CSV - Importing Literal from CSV"); $this->importLiteral($targetProperty, $resource, $csvRow, $csvColumn); } else { // Deal with the column value as a resource existing in the Knowledge Base. common_Logger::t("CSV - Importing Resource from CSV"); $this->importResource($targetProperty, $resource, $csvRow, $csvColumn); } } } if ($valid) { // Deal with default values. $this->importStaticData($this->options['staticMap'], $this->options['map'], $resource); // Apply 'resourceImported' callbacks. foreach ($this->resourceImported as $callback) { $callback($resource); } $createdResources++; } else { $resource->delete(); } } helpers_TimeOutHelper::reset(); } $this->addOption('to_import', count($csvData)); $this->addOption('imported', $createdResources); $report = $this->getResult($createdResources); return $report; }
/** * Compile the given $test into PHP source code for maximum performance. The file will be stored * into PRIVATE_DIRECTORY/compact-test.php. * * @param AssessmentTest $test */ protected function compileTest(AssessmentTest $test) { // Compiling a test may require extra processing time. helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::SHORT); $compiledDocDir = $this->getPrivateDirectory()->getPath(); $compiledDocPath = $compiledDocDir . TAOQTITEST_COMPILED_FILENAME; $phpCompiledDoc = new PhpDocument('2.1'); $phpCompiledDoc->setDocumentComponent($test); $phpCompiledDoc->save($compiledDocPath); common_Logger::d("QTI-PHP Test Compilation file registered at '" . $compiledDocPath . "'."); }