load the file content, parse it  and build the a QTI_Item instance

@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@param boolean resolveXInclude
@return \oat\taoQtiItem\model\qti\Item
542737
public function load($resolveXInclude = false){
        
        $returnValue = null;

        if(!$this->valid){
            libxml_use_internal_errors(true); //retrieve errors if no validation has been done previously
        }

        //load it using the DOMDocument library
        $xml = new DOMDocument();
        
        switch($this->sourceType){
            case self::SOURCE_FLYFILE:
                if ($this->source->exists()) {
                    $xml->load($this->source->read());
                }
                break;
            case self::SOURCE_FILE:
                $xml->load($this->source);
                break;
            case self::SOURCE_URL:
                $xmlContent = tao_helpers_Request::load($this->source, true);
                $xml->loadXML($xmlContent);
                break;
            case self::SOURCE_STRING:
                $xml->loadXML($this->source);
                break;
        }

        if($xml !== false){

            $basePath = '';
            if($this->sourceType == self::SOURCE_FILE || $this->sourceType == self::SOURCE_URL){
                $basePath = dirname($this->source).'/';
            }
            //build the item from the xml
            $parserFactory = new ParserFactory($xml, $basePath);
            try{
                $returnValue = $parserFactory->load();
            }catch(UnsupportedQtiElement $e){
                $this->addError($e);
            }

            if(!$this->valid){
                $this->valid = true;
                libxml_clear_errors();
            }
        }else if(!$this->valid){
            $this->addErrors(libxml_get_errors());
            libxml_clear_errors();
        }

        return $returnValue;
    }
193126
private function extractXinclude(Element $element){
        if($element instanceof Container){
            foreach($element->getElements('oat\taoQtiItem\model\qti\Xinclude') as $xinclude){
                $this->addAsset('xinclude', $xinclude->attr('href'));
            }
        }
    }
138703
@Override
	protected List<File> resolve(String fqtn) throws Exception {
		if(supportLogger.isDebugEnabled()) supportLogger.debug(Logs.LOG_01,
				ansiString(GREEN, fqtn)
		);

		StringTokenizer tokenizer = new StringTokenizer(fqtn, ":", false);
		String groupId = tokenizer.nextToken();
		String templateId = tokenizer.nextToken();
		String version = tokenizer.nextToken();

		return mvnDependencyResolver.resolve(groupId, templateId, version);
	}
685980
protected function _parseIncludeCallback($m) {
        $file = $this->resolve(RESOLVE_TEMPLATE, $m[1]) . '.tpl';

        $content = "";
        if ($this->_template->getFile() != $file) {
            if (file_exists($file)) {
                if (isset($m[4])) //precised time cache
                {
                    $t = new Template($m[1], 'tplInclude_' . $this->_template->getName() . '_' . $m[4] . '_' . Request::instance()->lang . '_' . $this->_includeI . '_', $m[4]);
                }
                else {
                    $t = new Template($m[1], 'tplInclude_' . $this->_template->getName() . '_' . Request::instance()->lang . '_' . $this->_includeI . '_', 0);
                }

                $t->assign($this->_template->vars);
                $t->show(Template::TPL_COMPILE_TO_INCLUDE, Template::TPL_COMPILE_INCLUDE);

                if (file_get_contents($t->getFileCache())) {
                    $content = file_get_contents($t->getFileCache());
                }

                $this->_includeI++;
            }
            else {
                $this->addError('Template "' . $file . '" can\'t be included', __FILE__, __LINE__, ERROR_FATAL);
            }
        }

        return $content;
    }
41304
public function resolveFileMenu()
    {
        $file_index = [];
        $files = $this->files;
        foreach ($files as $key => $file) {
            // 单页文件不做索引
            if (in_array($file['page_uuid'], $this->single_pages)) {
                continue;
            }
            // 标题索引处理
            $content = $this->fileSys->getContent($file['file_path']);
            $token = array_filter(explode("\n", $content['content']), function ($d){
                if (empty($d)) {
                    return false;
                }
                if (strpos($d, "\n#") === false && strpos($d, '#') !== 0 ) {
                    return false;
                }
                return true;
            });
            if (count($token)>0) {
                foreach ($token as &$value) {
                    $value = preg_replace_callback("|(#{1,6} )|", function($m){
                                return '';
                            }, $value);
                    $value = [
                        'title' => $value,
                        'href'  => '#'.$value,
                    ];
                }
            }
            $index = [
                'title' => $file['title'],
                'href'  => $file['href'],
                'uuid'  => $file['page_uuid'],
                'child' => $token
            ];
            $file_index[$file['page_uuid']] = $index;
        }
        $this->file_index = $file_index;
        // dd($file_index);
    }
827520
function resolveArgument(expr, argIndex) {
    if (typeof argIndex === 'undefined') {
        argIndex = 0;
    }
    if (!expr.arguments.length || !expr.arguments[argIndex]) {
        return;
    }
    this.applyPluginsBailResult('call require:commonjs:item', expr,
            this.evaluateExpression(expr.arguments[argIndex]));
}
464212
private function loadConfigFromCache()
    {
        /** @var \Core\Services\Contracts\Config $config */
        $config = DI::getInstance()->get('config');

        /** @noinspection PhpIncludeInspection */
        $config->set(null, require $this->cachedFile);

        return $config;
    }
1283286
public function resolve()
    {
        $instance = null;

        $args = [];

        if (isset($this->concrete)) {

            $reflected_class = new \ReflectionClass($this->concrete);

        } else {

            throw new ResolveException;
        }

        $reflected_method = $reflected_class->getConstructor();

        if ($reflected_method) {
            $args = $this->resolveArgs($reflected_method, $this->args);
        }

        $instance = $reflected_class->newInstanceArgs($args);

        foreach ($this->afters as $after) {

            $after($instance);
        }

        return $instance;
    }
1356516
public static function getDataForPattern($id, $resolveAlias = false)
    {
        $data = array();

        $id = Primer::cleanId($id);

        // Load the Patterns default data
        $defaultData = @file_get_contents(Primer::$PATTERN_PATH . '/' . $id . '/data.json');

        if ($defaultData) {
            $json = json_decode($defaultData);

            if ($json) {
                // Merge in the data
                $data += (array)$json;
            }
        }

        if ($resolveAlias) {
            // Parent data - e.g. elements/button is the parent of elements/button~primary
            $parentData = array();

            // Load parent data if this is inherit
            if (preg_match('/(.*?)~.*?/', $id, $matches)) {
                $parentData = FileSystem::getDataForPattern($matches[1]);
            }

            // Merge the parent and pattern data together, giving preference to the pattern data
            $data = array_replace_recursive((array)$parentData, (array)$data);
        }

        // Create the data structure
        $viewData = new ViewData($data);

        // Give the system a chance to mutate the data
        ViewData::fire($id, $viewData);

        // Return the data structure
        return $viewData;
    }
759945
public function resolve(
        ValueInterface $value,
        FixtureInterface $fixture,
        ResolvedFixtureSet $fixtureSet,
        array $scope,
        GenerationContext $context
    ): ResolvedValueWithFixtureSet {
        foreach ($this->resolvers as $resolver) {
            if ($resolver->canResolve($value)) {
                return $resolver->resolve($value, $fixture, $fixtureSet, $scope, $context);
            }
        }

        throw ResolverNotFoundExceptionFactory::createForValue($value);
    }
241894
function resolveIncludeDirectives(text, fileItem) {
	var result = [];

	// parse source code with esprima
	try {
		var srcParsed = esprima.parse(text);
	} catch (e) {
		logger.error(buildErrMsg(fileItem.ancestor, 'Failed to parse a [%s] JavaScript file. Reason : [%s]', fileItem.filePath, e));
		throw buildShortErrMsg(fileItem.ancestor, 'Failed to parse a [%s] JavaScript file. Reason : [%s]', path.basename(fileItem.filePath), e)
	}

	// iterating over and looking for include directives
	for (var key in srcParsed.body) {
		var item = srcParsed.body[key];

		// resolve include directive from dom item
		var includeDirective = resolveIncludeDirectiveDom(item);
		if (includeDirective != null) {
			result.push(includeDirective);
		}
	}

	return result;
}
995136
public function packItem(core_kernel_classes_Resource $item, $lang, Directory $directory)
    {
        //use the QtiParser to transform the QTI XML into an assoc array representation
        $content = $this->getXmlByItem($item, $lang);
        //load content
        $qtiParser = new QtiParser($content);
        //validate it
        $qtiParser->validate();
        if (!$qtiParser->isValid()) {
            throw new common_Exception('Invalid QTI content : ' . $qtiParser->displayErrors(false));
        }

        //parse
        $qtiItem = $qtiParser->load();

        return $this->packQtiItem($item, $lang, $qtiItem, $directory);

    }
497312
public function resolve(
        ValueInterface $value,
        FixtureInterface $fixture,
        ResolvedFixtureSet $fixtureSet,
        array $scope,
        GenerationContext $context
    ): ResolvedValueWithFixtureSet {
        if (null === $this->resolver) {
            throw ResolverNotFoundExceptionFactory::createUnexpectedCall(__METHOD__);
        }

        $quantifier = $value->getQuantifier();
        if ($quantifier instanceof ValueInterface) {
            $resolvedSet = $this->resolver->resolve($quantifier, $fixture, $fixtureSet, $scope, $context);
            list($quantifier, $fixtureSet) = [$resolvedSet->getValue(), $resolvedSet->getSet()];

            if (false === is_int($quantifier) && false === is_string($quantifier)) {
                throw UnresolvableValueExceptionFactory::createForInvalidResolvedQuantifierTypeForOptionalValue($value, $quantifier);
            }
        }

        $realValue = (mt_rand(0, 99) < $quantifier)
            ? $value->getFirstMember()
            : $value->getSecondMember()
        ;
        if ($realValue instanceof ValueInterface) {
            return $this->resolver->resolve($realValue, $fixture, $fixtureSet, $scope, $context);
        }

        return new ResolvedValueWithFixtureSet($realValue, $fixtureSet);
    }
743437
public function import()
    {
        try {
            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(),
                true,
                true,
                true,
                $this->isMetadataGuardiansEnabled(),
                $this->isMetadataValidatorsEnabled(),
                $this->isItemMustExistEnabled(),
                $this->isItemMustBeOverwrittenEnabled()
            );
            \helpers_TimeOutHelper::reset();
            
            \tao_helpers_File::remove($package);
            if ($report->getType() !== \common_report_Report::TYPE_SUCCESS) {
                $message = __("An unexpected error occurred during the import of the IMS QTI Item Package. ");
                //get message of first error report
                if (!empty($report->getErrors())) {
                    $message .= $report->getErrors()[0]->getMessage();
                }
                $this->returnFailure(new \common_Exception($message));
            } 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);
        }
    }
1096079
public function getXmlByRdfItem(core_kernel_classes_Resource $item, $language = '')
    {
        $itemService = taoItems_models_classes_ItemsService::singleton();

        //check if the item is QTI item
        if (! $itemService->hasItemModel($item, array(ItemModel::MODEL_URI))) {
            throw new common_Exception('Non QTI item('.$item->getUri().') opened via QTI Service');
        }

        $file = $itemService->getItemDirectory($item, $language)->getFile(self::QTI_ITEM_FILE);
        return $file->read();
    }
930020
protected function initElements()
    {
        //create file upload form box
        $fileElt = \tao_helpers_form_FormFactory::getElement('source', 'AsyncFile');
        $fileElt->setDescription(__("Add a media file"));
        if (isset($_POST['import_sent_file'])) {
            $fileElt->addValidator(\tao_helpers_form_FormFactory::getValidator('NotEmpty'));
        } else {
            $fileElt->addValidator(\tao_helpers_form_FormFactory::getValidator('NotEmpty', array('message' => '')));
        }
        $fileElt->addValidators(array(
            \tao_helpers_form_FormFactory::getValidator('FileSize', array('max' => SystemHelper::getFileUploadLimit()))
        ));

        $this->form->addElement($fileElt);

        $langService = \tao_models_classes_LanguageService::singleton();
        $dataUsage = new \core_kernel_classes_Resource(TaoOntology::PROPERTY_STANCE_LANGUAGE_USAGE_DATA);
        $dataLang = \common_session_SessionManager::getSession()->getDataLanguage();
        $dataLang = 'http://www.tao.lu/Ontologies/TAO.rdf#Lang'.$dataLang;
        if(!is_null($this->instanceUri)){
            $instance = new \core_kernel_classes_Resource($this->instanceUri);
            $lang = $instance->getOnePropertyValue(new \core_kernel_classes_Property(MediaService::PROPERTY_LANGUAGE));
            if($lang instanceof \core_kernel_classes_Resource){
                $dataLang = $lang->getUri();
            }
        }
        
        $langOptions = array();
        foreach ($langService->getAvailableLanguagesByUsage($dataUsage) as $lang) {
            $langOptions[\tao_helpers_Uri::encode($lang->getUri())] = $lang->getLabel();
        }
        $langElt = \tao_helpers_form_FormFactory::getElement('lang', 'Combobox');
        $langElt->setValue(\tao_helpers_Uri::encode($dataLang));
        $langElt->setOptions($langOptions);
        $this->form->addElement($langElt);


        $this->form->createGroup('options', __('Media Options'), array(
            $langElt
        ));

        $fileSentElt = \tao_helpers_form_FormFactory::getElement('import_sent_file', 'Hidden');
        $fileSentElt->setValue(1);
        $this->form->addElement($fileSentElt);

        if (!is_null($this->instanceUri)) {
            $instanceElt = \tao_helpers_form_FormFactory::getElement('instanceUri', 'Hidden');
            $instanceElt->setValue($this->instanceUri);
            $this->form->addElement($instanceElt);
        }

    }
952084
public function resolve()
    {
        $originFile = $this->file->getPhysicalFile();

        // force format storage directory
        $this->filesystem->mkdir(
            $relatedDestDir = sprintf('%s/%s',
                dirname($originFile->getRealPath()),
                $this->inflector->slugify($this->format->getId(), '_')
            )
        );

        // format call
        $this->formatter
            ->open($originFile->getRealPath())
            ->crop(
                new Point($this->options->x, $this->options->y),
                new Box($this->options->width, $this->options->height)
            )
            ->save($formattedFileName = sprintf('%s/%s',
                $relatedDestDir,
                $originFile->getBasename()
            ))
        ;

        // File object creation (if required)
        $file = $this->fileDomain->create(new PhysicalFile($formattedFileName));

        $this->formattedImage = $this->formattedImageLoader->retrieveByFile($file)
            ?: new $this->formattedImageClass()
        ;
        $this->formattedImage
            ->setFormat($this->format)
            ->setFile($file)
        ;

        $this->assertEntityIsValid($this->formattedImage, array('FormattedImage', 'creation'));

        $this->fireEvent(
            FormattedImageEvents::FORMATTED_IMAGE_CREATED,
            new FormattedImageEvent($this->formattedImage, $this)
        );

        return $this->formattedImage;
    }