Questions.

@param Bookboon $bookboon
@param array $answerIds array of answer ids, can be empty
@param string $rootSegmentId
@return BookboonResponse
@throws \Bookboon\Api\Exception\UsageException
497982
public static function get(
        Bookboon $bookboon,
        array $answerIds = [],
        string $rootSegmentId = ''
    ) : BookboonResponse {
        $url = $rootSegmentId == '' ? '/questions' : '/questions/' . $rootSegmentId;
        $bResponse =  $bookboon->rawRequest($url, ['answer' => $answerIds]);

        $bResponse->setEntityStore(
            new EntityStore(Question::getEntitiesFromArray($bResponse->getReturnArray()))
        );

        return $bResponse;
    }
1264842
public static function calculate_question_categories($backupid, $contextid) {
        global $DB;

        // First step, annotate all the categories for the given context (course/module)
        // i.e. the whole context questions bank
        $DB->execute("INSERT INTO {backup_ids_temp} (backupid, itemname, itemid)
                      SELECT ?, 'question_category', id
                        FROM {question_categories}
                       WHERE contextid = ?", array($backupid, $contextid));

        // Now, based in the annotated questions, annotate all the categories they
        // belong to (whole context question banks too)
        // First, get all the contexts we are going to save their question bank (no matter
        // where they are in the contexts hierarchy, transversals... whatever)
        $contexts = $DB->get_fieldset_sql("SELECT DISTINCT qc2.contextid
                                             FROM {question_categories} qc2
                                             JOIN {question} q ON q.category = qc2.id
                                             JOIN {backup_ids_temp} bi ON bi.itemid = q.id
                                            WHERE bi.backupid = ?
                                              AND bi.itemname = 'question'
                                              AND qc2.contextid != ?", array($backupid, $contextid));
        // And now, simply insert all the question categories (complete question bank)
        // for those contexts if we have found any
        if ($contexts) {
            list($contextssql, $contextparams) = $DB->get_in_or_equal($contexts);
            $params = array_merge(array($backupid), $contextparams);
            $DB->execute("INSERT INTO {backup_ids_temp} (backupid, itemname, itemid)
                          SELECT ?, 'question_category', id
                            FROM {question_categories}
                           WHERE contextid $contextssql", $params);
        }
    }
824572
public static function getTree(
        Bookboon $bookboon,
        array $blacklistedCategoryIds = [],
        int $depth = 2
    ) : BookboonResponse {
        $bResponse = $bookboon->rawRequest('/categories', ['depth' => $depth]);

        $categories = $bResponse->getReturnArray();

        if (count($blacklistedCategoryIds) !== 0) {
            self::recursiveBlacklist($categories, $blacklistedCategoryIds);
        }

        $bResponse->setEntityStore(
            new EntityStore(Category::getEntitiesFromArray($categories))
        );

        return $bResponse;
    }
715400
public function get($id, $rootId=NULL, array $columns=[])
    {
        $columns = $this->pickColumns($columns);
        $columnsId = $this->getColumnsCacheId($columns);

        if (isset($this->_hierachyCache[$columnsId][$id])) {
            return $this->_hierachyCache[$columnsId][$id];
        }

        // If we have a root id, fill the cache by fetching the whole tree
        if ($rootId) {
            $this->tree($rootId, $columns);
        }

        // After retrieving the tree, look if it is now in cache
        if (isset($this->_hierachyCache[$columnsId][$id])) {
            return $this->_hierachyCache[$columnsId][$id];
        }

        $result = $this->queryTreeById($id)
                       ->get($this->toSelectColumns($columns));

        $this->fillNodeCache($columnsId, $result);

        if (isset($this->_hierachyCache[$columnsId][$id])) {
            return $this->_hierachyCache[$columnsId][$id];
        }

    }
86366
public function addEmails($bookID, $emails, $additionalParams = [])
    {
        if (empty($bookID) || empty($emails)) {
            return $this->handleError('Empty book id or emails');
        }

        $data = array(
          'emails' => json_encode($emails),
        );

        if ($additionalParams) {
            $data = array_merge($data, $additionalParams);
        }

        $requestResult = $this->sendRequest('addressbooks/' . $bookID . '/emails', 'POST', $data);

        return $this->handleResult($requestResult);
    }
864224
public static function search(
        Bookboon $bookboon,
        string $query,
        int $limit = 10,
        int $offset = 0,
         array $bookTypes = ['pdf']
    ) : BookboonResponse {
        $bResponse = $bookboon->rawRequest('/search', ['q' => $query, 'limit' => $limit, 'offset' => $offset, 'bookType' => join(',', $bookTypes)]);

        $bResponse->setEntityStore(
            new EntityStore(Book::getEntitiesFromArray($bResponse->getReturnArray()))
        );

        return $bResponse;
    }
139058
public function getChildrenCount($tagId, array $translations = null, $useAlwaysAvailable = true)
    {
        $query = $this->createTagCountQuery($translations, $useAlwaysAvailable);
        $query->where(
            $query->expr->lAnd(
                $query->expr->eq(
                    $this->handler->quoteColumn('parent_id', 'eztags'),
                    $query->bindValue($tagId, null, PDO::PARAM_INT)
                ),
                $query->expr->eq($this->handler->quoteColumn('main_tag_id', 'eztags'), 0)
            )
        );

        $statement = $query->prepare();
        $statement->execute();

        $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

        return (int) $rows[0]['count'];
    }
268536
public static function view_book($bookid, $chapterid = 0) {
        global $DB, $CFG;
        require_once($CFG->dirroot . "/mod/book/lib.php");
        require_once($CFG->dirroot . "/mod/book/locallib.php");

        $params = self::validate_parameters(self::view_book_parameters(),
                                            array(
                                                'bookid' => $bookid,
                                                'chapterid' => $chapterid
                                            ));
        $bookid = $params['bookid'];
        $chapterid = $params['chapterid'];

        $warnings = array();

        // Request and permission validation.
        $book = $DB->get_record('book', array('id' => $bookid), '*', MUST_EXIST);
        list($course, $cm) = get_course_and_cm_from_instance($book, 'book');

        $context = context_module::instance($cm->id);
        self::validate_context($context);

        require_capability('mod/book:read', $context);

        $chapters = book_preload_chapters($book);
        $firstchapterid = 0;
        $lastchapterid = 0;

        foreach ($chapters as $ch) {
            if ($ch->hidden) {
                continue;
            }
            if (!$firstchapterid) {
                $firstchapterid = $ch->id;
            }
            $lastchapterid = $ch->id;
        }

        if (!$chapterid) {
            // Trigger the module viewed events since we are displaying the book.
            book_view($book, null, false, $course, $cm, $context);
            $chapterid = $firstchapterid;
        }

        // Check if book is empty (warning).
        if (!$chapterid) {
            $warnings[] = array(
                'item' => 'book',
                'itemid' => $book->id,
                'warningcode' => '1',
                'message' => get_string('nocontent', 'mod_book')
            );
        } else {
            $chapter = $DB->get_record('book_chapters', array('id' => $chapterid, 'bookid' => $book->id));
            $viewhidden = has_capability('mod/book:viewhiddenchapters', $context);

            if (!$chapter or ($chapter->hidden and !$viewhidden)) {
                throw new moodle_exception('errorchapter', 'mod_book');
            }

            // Trigger the chapter viewed event.
            $islastchapter = ($chapter->id == $lastchapterid) ? true : false;
            book_view($book, $chapter, $islastchapter, $course, $cm, $context);
        }

        $result = array();
        $result['status'] = true;
        $result['warnings'] = $warnings;
        return $result;
    }
278408
public static function getDownloadUrl(Bookboon $bookboon, string $categoryId, array $variables) : string
    {
        $bResponse = $bookboon->rawRequest("/categories/$categoryId/download", $variables, ClientInterface::HTTP_POST);

        return $bResponse->getReturnArray()['url'];
    }
359915
public function findOneByPageIdAndByLanguageId($pageId, $languageId)
    {
        $documentCollection = $this->findByPageIdAndByLanguageId($pageId, $languageId);
        return reset($documentCollection);
    }
473188
public function submit(Bookboon $bookboon, string $bookId) : void
    {
        if (Entity::isValidUUID($bookId)) {
            $bookboon->rawRequest("/books/$bookId/review", $this->getData(), ClientInterface::HTTP_POST);
        }
    }
276674
private function addMonologSection(ArrayNodeDefinition $rootNode)
    {
        $rootNode
            ->children()
                ->arrayNode('monolog')
                    ->canBeUnset()
                    ->children()
                        ->scalarNode('client')->isRequired()->end()
                        ->scalarNode('key')->isRequired()->end()
                        ->scalarNode('formatter')->end()
                    ->end()
                ->end()
            ->end();
    }
1277396
public function campaignCost($bookID)
    {
        if (empty($bookID)) {
            return $this->handleError('Empty book id');
        }

        $requestResult = $this->sendRequest('addressbooks/' . $bookID . '/cost');

        return $this->handleResult($requestResult);
    }
654002
protected function add_question_question_answers($element) {
        // Check $element is one nested_backup_element
        if (! $element instanceof backup_nested_element) {
            throw new backup_step_exception('question_answers_bad_parent_element', $element);
        }

        // Define the elements
        $answers = new backup_nested_element('answers');
        $answer = new backup_nested_element('answer', array('id'), array(
            'answertext', 'answerformat', 'fraction', 'feedback',
            'feedbackformat'));

        // Build the tree
        $element->add_child($answers);
        $answers->add_child($answer);

        // Set the sources
        $answer->set_source_table('question_answers', array('question' => backup::VAR_PARENTID), 'id ASC');

        // Aliases
        $answer->set_source_alias('answer', 'answertext');

        // don't need to annotate ids nor files
    }
250551
public static function submit_answers($surveyid, $answers) {
        global $DB, $USER;

        $params = self::validate_parameters(self::submit_answers_parameters(),
                                            array(
                                                'surveyid' => $surveyid,
                                                'answers' => $answers
                                            ));
        $warnings = array();

        // Request and permission validation.
        $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
        list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');

        $context = context_module::instance($cm->id);
        self::validate_context($context);
        require_capability('mod/survey:participate', $context);

        if (survey_already_done($survey->id, $USER->id)) {
            throw new moodle_exception("alreadysubmitted", "survey");
        }

        // Build the answers array. Data is cleaned inside the survey_save_answers function.
        $answers = array();
        foreach ($params['answers'] as $answer) {
            $key = $answer['key'];
            $answers[$key] = $answer['value'];
        }

        survey_save_answers($survey, $answers, $course, $context);

        $result = array();
        $result['status'] = true;
        $result['warnings'] = $warnings;
        return $result;
    }
1215732
protected function createTree(&$keyParts, TreeNode $rootNode) : TreeNode
    {
        if (!count($keyParts)) {
            return $rootNode;
        }

        $newKey  = array_shift($keyParts);
        $newNode = new self($rootNode, $newKey, null, $rootNode->getKeyDelimiter());
        $rootNode->addChild($newNode);

        return $this->createTree($keyParts, $newNode);
    }
1287209
public function deleteByRoot( $rootId = null, array $except = array() )
    {
        if ( null === $rootId )
        {
            $where = array( new Predicate\IsNull(
                'rootParagraphId'
            ) );
        }
        else
        {
            $where = array(
                'rootParagraphId' => (int) $rootId,
            );
        }

        if ( ! empty( $except ) )
        {
            $where[] = new Predicate\NotIn( 'id', $except );
        }

        $delete = $this->sql()
                       ->delete()
                       ->where( $where );

        $result = $this->sql()
                       ->prepareStatementForSqlObject( $delete )
                       ->execute();

        return $result->getAffectedRows();
    }