Add a category question entry based on the assessment title
@param array $xml the xml tree
@param array $questions the questions already parsed
977568
public function process_category($xml, &$questions) {
        $title = $this->getpath($xml, array('questestinterop', '#', 'assessment', 0, '@', 'title'), '', true);

        $dummyquestion = new stdClass();
        $dummyquestion->qtype = 'category';
        $dummyquestion->category = $this->cleaninput($this->clean_question_name($title));

        $questions[] = $dummyquestion;
    }
177271
public function loadXML($xml){
        if (!$xml){
            return false;
        }
        
        $this->data = array();
        
        //Categories first
        if ($xml->getName() == 'GetProductCategoriesForSKUResult' || $xml->getName() == 'GetProductCategoriesForASINResult'){
            $this->loadCategories($xml);
            return;
        }

        //Lowest Price uses different format
        if ($xml->getName() == 'GetLowestPricedOffersForSKUResult' || $xml->getName() == 'GetLowestPricedOffersForASINResult'){
            return $this->loadLowestPricedOfferXml($xml);
        }
        
        if ($xml->getName() != 'Product'){
            return;
        }
        
        //Identifiers
        if ($xml->Identifiers){
            foreach($xml->Identifiers->children() as $x){
                foreach($x->children() as $z){
                    $this->data['Identifiers'][$x->getName()][$z->getName()] = (string)$z;
                }
            }
        }
        
        //AttributeSets
        if ($xml->AttributeSets){
            $anum = 0;
            foreach($xml->AttributeSets->children('ns2',true) as $aset){
                foreach($aset->children('ns2',true) as $x){
                    if ($x->children('ns2',true)->count() > 0){
                        //another layer
                        foreach($x->children('ns2',true) as $y){
                            if ($y->children('ns2',true)->count() > 0){
                                //we need to go deeper
                                foreach($y->children('ns2',true) as $z){
                                    if ($z->children('ns2',true)->count() > 0){
                                        //we need to go deeper
                                        $this->log('Warning! Attribute '.$z->getName().' is too deep for this!', 'Urgent');
                                    } else {
                                        $this->data['AttributeSets'][$anum][$x->getName()][$y->getName()][$z->getName()] = (string)$z;
                                    }
                                }
                            } else {
                                $this->data['AttributeSets'][$anum][$x->getName()][$y->getName()] = (string)$y;
                            }
                        }

                    } else {
                        //Check for duplicates
                        if (array_key_exists('AttributeSets', $this->data) && 
                                array_key_exists($anum, $this->data['AttributeSets']) && 
                                array_key_exists($x->getName(), $this->data['AttributeSets'][$anum])){

                            //check for previous cases of duplicates
                            if (is_array($this->data['AttributeSets'][$anum][$x->getName()])){
                                $this->data['AttributeSets'][$anum][$x->getName()][] = (string)$x;
                            } else {
                                //first instance of duplicates, make into array
                                $temp = array($this->data['AttributeSets'][$anum][$x->getName()]);
                                $this->data['AttributeSets'][$anum][$x->getName()] = $temp;
                                $this->data['AttributeSets'][$anum][$x->getName()][] = (string)$x;
                            }
                        } else {
                            //no duplicates
                            $this->data['AttributeSets'][$anum][$x->getName()] = (string)$x;
                        }
                    }
                }
                $anum++;
            }
        }
        
        //Relationships
        if ($xml->Relationships){
            foreach($xml->Relationships->children() as $x){
                $temp = array();
                foreach($x->children() as $y){
                    foreach($y->children() as $z){
                        foreach($z->children() as $zzz){
                            $temp[$y->getName()][$z->getName()][$zzz->getName()] = (string)$zzz;
                        }
                    }
                }
                foreach($x->children('ns2',true) as $y){
                    $temp[$y->getName()] = (string)$y;
                }
                $this->data['Relationships'][$x->getName()][] = $temp;
            }
            //child relations use namespace but parent does not
            foreach($xml->Relationships->children('ns2',true) as $x){
                $temp = array();
                foreach($x->children() as $y){
                    foreach($y->children() as $z){
                        foreach($z->children() as $zzz){
                            $temp[$y->getName()][$z->getName()][$zzz->getName()] = (string)$zzz;
                        }
                    }
                }
                foreach($x->children('ns2',true) as $y){
                    $temp[$y->getName()] = (string)$y;
                }
                $this->data['Relationships'][$x->getName()][] = $temp;
            }
        }
        
        //CompetitivePricing
        if ($xml->CompetitivePricing){
            //CompetitivePrices
            foreach($xml->CompetitivePricing->CompetitivePrices->children() as $pset){
                $pnum = (string)$pset->CompetitivePriceId;
                $temp = (array)$pset->attributes();
                $belongs = $temp['@attributes']['belongsToRequester'];
                $con = $temp['@attributes']['condition'];
                $sub = $temp['@attributes']['subcondition'];
                $this->data['CompetitivePricing']['CompetitivePrices'][$pnum]['belongsToRequester'] = $belongs;
                $this->data['CompetitivePricing']['CompetitivePrices'][$pnum]['condition'] = $con;
                $this->data['CompetitivePricing']['CompetitivePrices'][$pnum]['subcondition'] = $sub;
                
                
                foreach($pset->Price->children() as $x){
                    //CompetitivePrice->Price
                    foreach($x->children() as $y){
                        $this->data['CompetitivePricing']['CompetitivePrices'][$pnum]['Price'][$x->getName()][$y->getName()] = (string)$y;
                    }
                    
                }
                
                $pnum++;
            }
            //NumberOfOfferListings
            if ($xml->CompetitivePricing->NumberOfOfferListings){
                foreach($xml->CompetitivePricing->NumberOfOfferListings->children() as $x){
                    $temp = (array)$x->attributes();
                    $att = $temp['@attributes']['condition'];
                    $this->data['CompetitivePricing']['NumberOfOfferListings'][$x->getName()][$att] = (string)$x;
                }
            }
            
            //TradeInValue
            if ($xml->CompetitivePricing->TradeInValue){
                foreach($xml->CompetitivePricing->TradeInValue->children() as $x){
                    $this->data['CompetitivePricing']['TradeInValue'][$x->getName()] = (string)$x;
                }
            }
        }
            
        
        //SalesRankings
        if ($xml->SalesRankings){
            foreach($xml->SalesRankings->children() as $x){
                $temp = array();
                foreach($x->children() as $y){
                    $temp[$y->getName()] = (string)$y;
                }
                $this->data['SalesRankings'][$x->getName()][] = $temp;
            }
        }
        
        //LowestOfferListings
        if ($xml->LowestOfferListings){
            $lnum = 0;
            foreach($xml->LowestOfferListings->children() as $x){
                //LowestOfferListing
                foreach($x->children() as $y){
                    if ($y->children()->count() > 0){
                        foreach($y->children() as $z){
                            if ($z->children()->count() > 0){
                                foreach($z->children() as $zzz){
                                    $this->data['LowestOfferListings'][$lnum][$y->getName()][$z->getName()][$zzz->getName()] = (string)$zzz;
                                }
                            } else {
                                $this->data['LowestOfferListings'][$lnum][$y->getName()][$z->getName()] = (string)$z;
                            }
                            
                        }
                    } else {
                        $this->data['LowestOfferListings'][$lnum][$y->getName()] = (string)$y;
                    }
                }
                $lnum++;
            }
        }
        
        //Offers
        if ($xml->Offers){
            $onum = 0;
            foreach($xml->Offers->children() as $x){
                //Offer
                foreach($x->children() as $y){
                    if ($y->children()->count() > 0){
                        foreach($y->children() as $z){
                            if ($z->children()->count() > 0){
                                foreach($z->children() as $zzz){
                                    $this->data['Offers'][$onum][$y->getName()][$z->getName()][$zzz->getName()] = (string)$zzz;
                                }
                            } else {
                                $this->data['Offers'][$onum][$y->getName()][$z->getName()] = (string)$z;
                            }
                            
                        }
                    } else {
                        $this->data['Offers'][$onum][$y->getName()] = (string)$y;
                    }
                }
                $onum++;
            }
        }
        
        
        
    }
766008
public function evaluateQuestion(array $question, PhpStringParser $parser, GeneratorDataObject $generator)
    {
        $iterator       = $this->iteratorValidator->retrieveValidIteration($question, $generator, $parser);
        $iteratorParser = clone $parser;

        foreach ($iterator as $iteration) {
            $iteratorParser->addVariable('iteration', $iteration);

            $origine            = $iteratorParser->parse($question['iteration']['retrieveBy']);
            $responseCollection = new PredefinedResponseCollection();

            foreach ($question['iteration']['response']['predefined'] as $predefinedResponse) {
                $responseCollection->append(
                    new PredefinedResponse(
                        $predefinedResponse['response'],
                        $iteratorParser->parse($predefinedResponse['text']),
                        $predefinedResponse['response']
                    )
                );
            }

            $questionWithPredefinedResponse = new QuestionWithPredefinedResponse(
                $iteratorParser->parse($question['iteration']['text']),
                'set_predefined_' . ucfirst($question['dtoAttribute']) . $origine,
                $responseCollection
            );

            $questionWithPredefinedResponse->setDefaultResponse(
                (isset($question['iteration']['response']['default']) === true) ?
                    $iteratorParser->parse($question['iteration']['response']['default']) : null
            )->setRequired($question['required'])
             ->setResponseType(new QuestionResponseTypeEnum($question['iteration']['response']['type']));

            $response = $this->context->askCollection($questionWithPredefinedResponse);

            $questionName = $question['setter'];
            if ($response !== null) {
                $generator->getDto()->$questionName($origine, $response);
            }
        }

        return $generator;
    }
872515
public function import_combined_feedback($qo, $questionxml, $withshownumpartscorrect = false) {
        $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
        foreach ($fields as $field) {
            $qo->$field = $this->import_text_with_files($questionxml,
                    array('#', $field, 0), '', $this->get_format($qo->questiontextformat));
        }

        if ($withshownumpartscorrect) {
            $qo->shownumcorrect = array_key_exists('shownumcorrect', $questionxml['#']);

            // Backwards compatibility.
            if (array_key_exists('correctresponsesfeedback', $questionxml['#'])) {
                $qo->shownumcorrect = $this->trans_single($this->getpath($questionxml,
                        array('#', 'correctresponsesfeedback', 0, '#'), 1));
            }
        }
    }
11378
public function process_essay($quest, &$questions) {

        $question = $this->process_common($quest);
        $question->qtype = 'essay';

        $question->feedback = array();
        // Not sure where to get the correct answer from?
        foreach ($quest->feedback as $feedback) {
            // Added this code to put the possible solution that the
            // instructor gives as the Moodle answer for an essay question.
            if ($feedback->ident == 'solution') {
                $question->graderinfo = $this->cleaned_text_field($feedback->text);
            }
        }
        // Added because essay/questiontype.php:save_question_option is expecting a
        // fraction property - CT 8/10/06.
        $question->fraction[] = 1;
        $question->defaultmark = 1;
        $question->responseformat = 'editor';
        $question->responserequired = 1;
        $question->responsefieldlines = 15;
        $question->attachments = 0;
        $question->attachmentsrequired = 0;
        $question->responsetemplate = $this->text_field('');

        $questions[] = $question;
    }
786844
public function seeXmlResponseEquals($xml)
    {
        \PHPUnit\Framework\Assert::assertXmlStringEqualsXmlString($this->connectionModule->_getResponseContent(), $xml);
    }
1079211
protected function customNestedSort( $xml ) {
		$array = [];

		//first, put them in ascending menu_order
		usort(
			$xml, function ( $a, $b ) {
				return ( $a['menu_order'] - $b['menu_order'] );
			}
		);

		// Start with book info
		foreach ( $xml as $p ) {
			if ( 'metadata' === $p['post_type'] ) {
				$array[] = $p;
				break;
			}
		}

		//now, list all front matter
		foreach ( $xml as $p ) {
			if ( 'front-matter' === $p['post_type'] ) {
				$array[] = $p;
			}
		}

		//now, list all parts, then their associated chapters
		foreach ( $xml as $p ) {
			if ( 'part' === $p['post_type'] ) {
				$array[] = $p;
				foreach ( $xml as $psub ) {
					if ( 'chapter' === $psub['post_type'] && $psub['post_parent'] === $p['post_id'] ) {
						$array[] = $psub;
					}
				}
			}
		}

		//now, list all back matter
		foreach ( $xml as $p ) {
			if ( 'back-matter' === $p['post_type'] ) {
				$array[] = $p;
			}
		}

		// Glossary
		foreach ( $xml as $p ) {
			if ( 'glossary' === $p['post_type'] ) {
				$array[] = $p;
			}
		}

		// Remaining custom post types
		$custom_post_types = apply_filters( 'pb_import_custom_post_types', [] );

		foreach ( $xml as $p ) {
			if ( in_array( $p['post_type'], $custom_post_types, true ) ) {
				$array[] = $p;
			}
		}

		return $array;
	}
1156582
protected function attach_nodes_to_categories() {
        foreach ($this->nodes as $node) {
            $parentcat = $node->parentcat;
            if (!isset($this->categories[$parentcat])) {
                throw new \coding_exception("Category $parentcat doesn't exist");
            } else {
                $this->categories[$parentcat]->add_node($node);
            }
        }
    }
260352
public function process_question(array $data, array $raw) {
        // Data added on the upgrade step 2011031000.
        $this->write_xml('essay', array(
            'id'                     => $this->converter->get_nextid(),
            'responseformat'         => 'editor',
            'responserequired'       => 1,
            'responsefieldlines'     => 15,
            'attachments'            => 0,
            'attachmentsrequired'    => 0,
            'graderinfo'             => '',
            'graderinfoformat'       => FORMAT_HTML,
            'responsetemplate'       => '',
            'responsetemplateformat' => FORMAT_HTML
        ), array('/essay/id'));
    }
1181982
private function pullQuestion($questionId, array $questions, array $decodedQuestions = [])
    {
        if (empty($decodedQuestions[$questionId])) {
            foreach ($questions as $index => $question) {
                if ($question->getId() === (int) $questionId && !empty($question->getMimeType())) {
                    $decodedQuestions[$questionId] = $this->itemSerializer->serialize($question, [Transfer::INCLUDE_SOLUTIONS]);
                    unset($questions[$index]);
                    break;
                }
            }
        }

        return !empty($decodedQuestions[$questionId]) ? $decodedQuestions[$questionId] : null;
    }
1225836
public function process_fib($xml, &$questions) {
        if ($this->getpath($xml, array('POOL', '#', 'QUESTION_FILLINBLANK'), false, false)) {
            $fibquestions = $this->getpath($xml,
                    array('POOL', '#', 'QUESTION_FILLINBLANK'), false, false);
        } else {
            return;
        }

        foreach ($fibquestions as $thisquestion) {

            $question = $this->process_common($thisquestion);

            $question->qtype = 'shortanswer';
            $question->usecase = 0; // Ignore case.

            $correctfeedback = $this->getpath($thisquestion,
                    array('#', 'GRADABLE', 0, '#', 'FEEDBACK_WHEN_CORRECT', 0, '#'),
                    '', true);
            $incorrectfeedback = $this->getpath($thisquestion,
                    array('#', 'GRADABLE', 0, '#', 'FEEDBACK_WHEN_INCORRECT', 0, '#'),
                    '', true);
            $answers = $this->getpath($thisquestion, array('#', 'ANSWER'), false, false);
            foreach ($answers as $answer) {
                $question->answer[] = $this->getpath($answer,
                        array('#', 'TEXT', 0, '#'), '', true);
                $question->fraction[] = 1;
                $question->feedback[] = $this->cleaned_text_field($correctfeedback);
            }
            $question->answer[] = '*';
            $question->fraction[] = 0;
            $question->feedback[] = $this->cleaned_text_field($incorrectfeedback);

            $questions[] = $question;
        }
    }
679675
public function add_category($newparent, $newcategory, $newinfo, $return = false, $newinfoformat = FORMAT_HTML,
            $idnumber = null) {
        global $DB;
        if (empty($newcategory)) {
            print_error('categorynamecantbeblank', 'question');
        }
        list($parentid, $contextid) = explode(',', $newparent);
        //moodle_form makes sure select element output is legal no need for further cleaning
        require_capability('moodle/question:managecategory', context::instance_by_id($contextid));

        if ($parentid) {
            if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
                print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
            }
        }

        if ((string) $idnumber === '') {
            $idnumber = null;
        } else if (!empty($contextid)) {
            // While this check already exists in the form validation, this is a backstop preventing unnecessary errors.
            if ($DB->record_exists('question_categories',
                    ['idnumber' => $idnumber, 'contextid' => $contextid])) {
                $idnumber = null;
            }
        }

        $cat = new stdClass();
        $cat->parent = $parentid;
        $cat->contextid = $contextid;
        $cat->name = $newcategory;
        $cat->info = $newinfo;
        $cat->infoformat = $newinfoformat;
        $cat->sortorder = 999;
        $cat->stamp = make_unique_id_code();
        if ($idnumber) {
            $cat->idnumber = $idnumber;
        }
        $categoryid = $DB->insert_record("question_categories", $cat);

        // Log the creation of this category.
        $category = new stdClass();
        $category->id = $categoryid;
        $category->contextid = $contextid;
        $event = \core\event\question_category_created::create_from_question_category_instance($category);
        $event->trigger();

        if ($return) {
            return $categoryid;
        } else {
            redirect($this->pageurl);//always redirect after successful action
        }
    }
859899
public function removeQuestion(QuestionInterface $question)
    {
        if ($this->hasQuestion($question)) {
            $this->questions->removeElement($question);
            $question->setCategory(null);
        }

        return $this;
    }
355638
protected function add_question_datasets($element) {
        // Check $element is one nested_backup_element
        if (! $element instanceof backup_nested_element) {
            throw new backup_step_exception('question_datasets_bad_parent_element', $element);
        }

        // Define the elements
        $definitions = new backup_nested_element('dataset_definitions');
        $definition = new backup_nested_element('dataset_definition', array('id'), array(
            'category', 'name', 'type', 'options',
            'itemcount'));

        $items = new backup_nested_element('dataset_items');
        $item = new backup_nested_element('dataset_item', array('id'), array(
            'number', 'value'));

        // Build the tree
        $element->add_child($definitions);
        $definitions->add_child($definition);

        $definition->add_child($items);
        $items->add_child($item);

        // Set the sources
        $definition->set_source_sql('SELECT qdd.*
                                       FROM {question_dataset_definitions} qdd
                                       JOIN {question_datasets} qd ON qd.datasetdefinition = qdd.id
                                      WHERE qd.question = ?', array(backup::VAR_PARENTID));

        $item->set_source_table('question_dataset_items', array('definition' => backup::VAR_PARENTID));

        // Aliases
        $item->set_source_alias('itemnumber', 'number');

        // don't need to annotate ids nor files
    }
612827
def add_category_to_xml(xmldoc)
      return if category_name.to_s.empty?
      cat_elem = REXML::Element.new('category')

      if self.class::CATEGORY_DATA_TYPE == String
        cat_elem.text = @category_name.to_s
      elsif self.class::CATEGORY_DATA_TYPE == Hash
        cat_elem.add_element('name').text = @category_name.to_s
      else
        raise JSS::InvalidDataError, "Uknown CATEGORY_DATA_TYPE for class #{self.class}"
      end

      root = xmldoc.root

      if self.class::CATEGORY_SUBSET == :top
        root.add_element cat_elem
        return
      end

      parent = root.elements[self.class::CATEGORY_SUBSET.to_s]
      parent ||= root.add_element self.class::CATEGORY_SUBSET.to_s
      parent.add_element cat_elem
    end
569619
public function setXML(&$xml)
	{
		if (is_object($xml))
		{
			if ($group = $xml['group'])
			{
				$this->_xml[(string) $group] = $xml;
			}
			else
			{
				$this->_xml['_default'] = $xml;
			}

			if ($dir = $xml['addpath'])
			{
				$this->addElementPath(PATH_ROOT . str_replace('/', DS, (string) $dir));
			}
		}
	}
1270081
protected function loadCategories($xml){
        //Categories
        if (!$xml->Self){
            return false;
        }
        $cnum = 0;
        foreach($xml->children() as $x){
            $this->data['Categories'][$cnum] = $this->genHierarchy($x);
            $cnum++;
        }
    }