Post Questions.

@param Bookboon $bookboon
@param array $variables
@param string $rootSegmentId
@return BookboonResponse
@throws \Bookboon\Api\Exception\UsageException
429921
public static function send(
        Bookboon $bookboon,
        array $variables = [],
        string $rootSegmentId = ''
    ) : BookboonResponse {
        $url = $rootSegmentId == '' ? '/questions' : '/questions/' . $rootSegmentId;
        $bResponse = $bookboon->rawRequest($url, $variables, ClientInterface::HTTP_POST);
        return $bResponse;
    }
1284073
public static function recommendations(
        Bookboon $bookboon,
        array $bookIds = [],
        int $limit = 5,
        array $bookTypes = ['pdf']
    ) : BookboonResponse {
        $bResponse = $bookboon->rawRequest('/recommendations', ['limit' => $limit, 'book' => $bookIds, 'bookType' => join(',', $bookTypes)]);

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

        return $bResponse;
    }
641486
public function sendRaw($data, $rootNode, $endOfMessageDelimiter, $attributes=array(), $waitForReply=true)
    {

        $data = str_replace('<?xml version="1.0"?>', '', (string)$data);

        $data = new SimpleXMLElement("<{$rootNode}>$data</{$rootNode}>");

        foreach ($attributes as $attribute_name=>$attribute_value) {

            $data->addAttribute($attribute_name, $attribute_value);

        }

        $data = str_replace('<?xml version="1.0"?>', '', $data->asXML());

        $this->sendHistory[] = $data;

        $this->ssh->write($data."]]>]]>\n");

        if (!$waitForReply) {

            return true;

        }

        return $this->readReply($endOfMessageDelimiter);
    }
1272482
protected function buildPageIdRootline($pageId, $mountPoint = '')
    {
        $rootlinePageIds = [];

            /** @var $pageSelector PageRepository */
        $pageSelector = GeneralUtility::makeInstance(PageRepository::class);
        $rootline = $pageSelector->getRootLine($pageId, (string)$mountPoint);

        foreach ($rootline as $page) {
            if (Site::isRootPage($page)) {
                break;
            }

            array_unshift($rootlinePageIds, $page['pid']);
        }

        $rootlinePageIds[] = $pageId;

        return $rootlinePageIds;
    }
1228141
private function addSessionSection(ArrayNodeDefinition $rootNode)
    {
        $rootNode
            ->children()
                ->arrayNode('session')
                    ->canBeUnset()
                    ->children()
                        ->scalarNode('client')->isRequired()->end()
                        ->scalarNode('prefix')->defaultValue('session')->end()
                        ->scalarNode('ttl')->end()
                        ->booleanNode('locking')->defaultTrue()->end()
                        ->scalarNode('spin_lock_wait')->defaultValue(150000)->end()
                    ->end()
                ->end()
            ->end();
    }
1075823
public function create($rootPageId, $setHost = false)
    {
        if (!is_object($GLOBALS['TT'])) {
            $GLOBALS['TT'] = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TimeTracker\\TimeTracker');
            $GLOBALS['TT']->start();
        }

        $GLOBALS['TSFE'] = GeneralUtility::makeInstance(
            'TYPO3\\CMS\\Frontend\\Controller\\TypoScriptFrontendController',
            $GLOBALS['TYPO3_CONF_VARS'],
            $rootPageId,
            0
        );

        $GLOBALS['TSFE']->initFEuser();
        $GLOBALS['TSFE']->determineId();
        $GLOBALS['TSFE']->getPageAndRootline();
        $GLOBALS['TSFE']->initTemplate();
        $GLOBALS['TSFE']->getConfigArray();
        $GLOBALS['TSFE']->newCObj();

        if ($setHost) {
            $domains = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
                'domainName',
                'sys_domain',
                'hidden = 0 AND pid = "' . $rootPageId . '"'
            );

            if (count($domains)) {
                $_SERVER['HTTP_HOST'] = $domains[0]['domainName'];
            }
        }
    }
1104016
public function getEntityNavigation($rootPage = null, $mode = AbstractQuery::HYDRATE_ARRAY, $cacheKey = null)
    {
        /** @var $repo  PageRepository */
        $this->setCacheKey($cacheKey);
        $repo  = $this->getRepository();
        $query = $this->addHints($repo->getNodesHierarchyQuery($rootPage));
        $query = $this->setCacheFlag($query);

        return $query->execute([], $mode);
    }
1068557
public function createNewErrorNode($nodeId, $name, $parentId, $siteId, $language, $template)
    {
        $node = $this->initializeNode(NodeInterface::ROOT_NODE_ID, $language, $siteId);
        $node->setNodeId($nodeId);
        $node->setParentId($parentId);
        $node->setNodeType(ReadNodeInterface::TYPE_ERROR);
        $node->setName($name);
        $node->setInFooter(false);
        $node->setInMenu(false);
        $node->setTemplate($template);
        $node->setOrder(-1);
        $node = $this->setVersionName($node);

        $this->eventDispatcher->dispatch(NodeEvents::NODE_CREATION, new NodeEvent($node));

        return $node;
    }
173878
public function addCategoryToAllowedRoots($categoryId)
    {
        if (null === ($roots = $this->getUserAllowedRoots())) {
            return;
        }

        $categoryId = (int) $categoryId;
        $user = $this->getUser();

        /** @var StringUtil $stringUtil */
        $stringUtil = $this->framework->getAdapter(StringUtil::class);

        // Add the permissions on group level
        if ('custom' !== $user->inherit) {
            $groups = $this->db->fetchAll('SELECT id, newscategories, newscategories_roots FROM tl_user_group WHERE id IN('.\implode(',', \array_map('intval', $user->groups)).')');

            foreach ($groups as $group) {
                $permissions = $stringUtil->deserialize($group['newscategories'], true);

                if (\in_array('manage', $permissions, true)) {
                    $categoryIds = $stringUtil->deserialize($group['newscategories_roots'], true);
                    $categoryIds[] = $categoryId;

                    $this->db->update('tl_user_group', ['newscategories_roots' => \serialize($categoryIds)], ['id' => $group['id']]);
                }
            }
        }

        // Add the permissions on user level
        if ('group' !== $user->inherit) {
            $userData = $this->db->fetchAssoc('SELECT newscategories, newscategories_roots FROM tl_user WHERE id=?', [$user->id]);
            $permissions = $stringUtil->deserialize($userData['newscategories'], true);

            if (\in_array('manage', $permissions, true)) {
                $categoryIds = $stringUtil->deserialize($userData['newscategories_roots'], true);
                $categoryIds[] = $categoryId;

                $this->db->update('tl_user', ['newscategories_roots' => \serialize($categoryIds)], ['id' => $user->id]);
            }
        }

        // Add the new element to the user object
        $user->newscategories_roots = \array_merge($roots, [$categoryId]);
    }
629117
public void surveyPage(PageFormat pageFormat, Graphics2D g2d, boolean bPrintHeader)
    {
        pageRect = new Rectangle((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY(), (int)pageFormat.getImageableWidth(), (int)pageFormat.getImageableHeight());

        FontMetrics fm = g2d.getFontMetrics();
        int textHeight = fm.getHeight();
        if (bPrintHeader)
        {
            headerHeight = textHeight + HEADER_MARGIN + BORDER;
            footerHeight = textHeight + HEADER_MARGIN + BORDER;
        }
    }
679300
public function createPage(
        $refEntityType,
        $pageTitle,
        $locale,
        Node $parentNode = null)
    {
        $user = $this->getAdminUser();

        $newPage = $this->createNewPage($refEntityType, $pageTitle);
        if (null !== $parentNode) {
            $parentNodeTranslation = $parentNode->getNodeTranslation($locale, true);
            $parentNodeVersion = $parentNodeTranslation->getPublicNodeVersion();
            $parentPage = $parentNodeVersion->getRef($this->em);
            $newPage->setParent($parentPage);
        }

        /* @var Node $nodeNewPage */
        $nodeNewPage = $this->em->getRepository('KunstmaanNodeBundle:Node')->createNodeFor($newPage, $locale, $user);
        $nodeTranslation = $nodeNewPage->getNodeTranslation($locale, true);
        if (null !== $parentNode) {
            $weight = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')->getMaxChildrenWeight(
                    $parentNode,
                    $locale
                ) + 1;
            $nodeTranslation->setWeight($weight);
        }

        if ($newPage->isStructureNode()) {
            $nodeTranslation->setSlug('');
        }

        $this->em->persist($nodeTranslation);
        $this->em->flush();

        $nodeVersion = $nodeTranslation->getPublicNodeVersion();

        $this->eventDispatcher->dispatch(
            Events::ADD_NODE,
            new NodeEvent(
                $nodeNewPage, $nodeTranslation, $nodeVersion, $newPage
            )
        );

        return $nodeTranslation;
    }
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;
    }
1353354
public function getTopKeyWordsWithoutHits(int $rootPageId, int $days = 30, int $limit = 10) : array
    {
        return $this->getTopKeyWordsWithOrWithoutHits($rootPageId, $days, $limit, true);
    }
10785
public function createPage(
        SiteEntity $site,
        $pageData,
        $publishPage = false,
        $doFlush = true
    ) {
        if (empty($pageData['createdByUserId'])) {
            throw new PageException('CreatedByUserId is required to create a page.');
        }
        if (empty($pageData['createdReason'])) {
            $pageData['createdReason'] = Tracking::UNKNOWN_REASON;
        }
        if (empty($pageData['author'])) {
            throw new PageException('Author is required to create a page.');
        }
        $revision = new Revision(
            $pageData['createdByUserId'],
            $pageData['createdReason']
        );
        $revision->setAuthor($pageData['author']);

        // we should not have an Id on page create
        unset($pageData['pageId']);

        $page = new PageEntity(
            $pageData['createdByUserId'],
            $pageData['createdReason']
        );
        $page->populate($pageData);

        $page->setSite($site);

        $this->assertCanCreateSitePage(
            $page->getSite(),
            $page->getName(),
            $page->getPageType()
        );

        if (!$publishPage) {
            $page->setStagedRevision($revision);
        } else {
            $page->setPublishedRevision($revision);
        }

        $page->addRevision($revision);

        $this->_em->persist($revision);
        $this->_em->persist($page);

        if ($doFlush) {
            $this->_em->flush(
                [
                    $revision,
                    $page
                ]
            );
        }

        return $page;
    }
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'];
    }
1092566
public static function getList($rootPid, $languageId = null)
    {
        $sitemapList = array();
        $pageList    = array();

        $typo3Pids = array();

        $query = 'SELECT ts.*
                    FROM tx_metaseo_sitemap ts
                            INNER JOIN pages p
                              ON    p.uid = ts.page_uid
                                AND p.deleted = 0
                                AND p.hidden = 0
                                AND p.tx_metaseo_is_exclude = 0
                                AND ' . DatabaseUtility::conditionNotIn('p.doktype', self::getDoktypeBlacklist()) . '
                   WHERE ts.page_rootpid = ' . (int)$rootPid . '
                     AND ts.is_blacklisted = 0';

        if ($languageId !== null) {
            $query .= ' AND ts.page_language = ' . (int)$languageId;
        }
        $query .= ' ORDER BY
                        ts.page_depth ASC,
                        p.pid ASC,
                        p.sorting ASC';
        $resultRows = DatabaseUtility::getAll($query);

        if (!$resultRows) {

            return self::getListArray(); //empty
        }

        foreach ($resultRows as $row) {
            $sitemapList[] = $row;

            $sitemapPageId             = $row['page_uid'];
            $typo3Pids[$sitemapPageId] = (int)$sitemapPageId;
        }

        if (!empty($typo3Pids)) {
            $query    = 'SELECT *
                           FROM pages
                          WHERE ' . DatabaseUtility::conditionIn('uid', $typo3Pids);
            $pageList = DatabaseUtility::getAllWithIndex($query, 'uid');

            if (empty($pageList)) {

                return self::getListArray(); //empty
            }
        }

        return self::getListArray($sitemapList, $pageList);
    }
164104
public function importBlog(array $data, $rootPath, User $owner)
    {
        $blogDatas = $data['data'];
        $optionsData = $blogDatas['options'];

        $blogOptions = new BlogOptions();
        $blogOptions
            ->setAuthorizeComment($optionsData['authorize_comment'])
            ->setAuthorizeAnonymousComment($optionsData['authorize_anonymous_comment'])
            ->setPostPerPage($optionsData['post_per_page'])
            ->setAutoPublishPost($optionsData['auto_publish_post'])
            ->setAutoPublishComment($optionsData['auto_publish_comment'])
            ->setDisplayTitle($optionsData['display_title'])
            ->setBannerActivate($optionsData['banner_activate'])
            ->setDisplayPostViewCounter($optionsData['display_post_view_counter'])
            ->setBannerBackgroundColor($optionsData['banner_background_color'])
            ->setBannerHeight($optionsData['banner_height'])
            ->setBannerBackgroundImagePosition($optionsData['banner_background_image_position'])
            ->setBannerBackgroundImageRepeat($optionsData['banner_background_image_repeat'])
            ->setTagCloud($optionsData['tag_cloud']);

        if (isset($optionsData['display_full_posts'])) {
            $blogOptions->setDisplayFullPosts($optionsData['display_full_posts']);
        } else {
            $blogOptions->setDisplayFullPosts(false);
        }

        if (isset($optionsData['comment_moderation_mode'])) {
            $blogOptions->setCommentModerationMode($optionsData['comment_moderation_mode']);
        } else {
            $blogOptions->setCommentModerationMode(BlogOptions::COMMENT_MODERATION_ALL);
        }

        $blog = new Blog();
        if (isset($blogDatas['infos_path']) && null !== $blogDatas['infos_path']) {
            $infos = file_get_contents(
                $rootPath.DIRECTORY_SEPARATOR.$blogDatas['infos_path']
            );
            $blog->setInfos($infos);
        }
        $blog->setOptions($blogOptions);
        $this->objectManager->persist($blog);
        //flush, otherwise we dont have the website ID needed for building uploadPath for banner
        //$this->objectManager->forceFlush();

        //Copy banner bg image to web folder, old system, for compatibility
        if (isset($optionsData['banner_background_image']) && null !== $optionsData['banner_background_image'] && !filter_var($optionsData['banner_background_image'], FILTER_VALIDATE_URL)) {
            $bannerPath = $rootPath.DIRECTORY_SEPARATOR.$optionsData['banner_background_image'];
            if (file_exists($bannerPath)) {
                $publicFile = $this->fileUtils->createFile(new File($bannerPath));
                $blog->getResourceNode()->setPoster($publicFile->getUrl());
            }
        }

        $postsDatas = $blogDatas['posts'];
        $posts = new ArrayCollection();

        foreach ($postsDatas as $postsData) {
            $tagsDatas = $postsData['tags'];
            $tags = [];
            foreach ($tagsDatas as $tagsData) {
                $tags[] = $tagsData['name'];
            }
            $post = new Post();
            //insert tags
            $event = new GenericDataEvent([
                'tags' => array_values($tags),
                'data' => [
                    [
                        'class' => 'Icap\BlogBundle\Entity\Post',
                        'id' => $post->getUuid(),
                        'name' => $post->getTitle(),
                    ],
                ],
                'replace' => true,
            ]);
            $this->eventDispatcher->dispatch('claroline_tag_multiple_data', $event);

            $commentsDatas = $postsData['comments'];
            $comments = new ArrayCollection();
            foreach ($commentsDatas as $commentsData) {
                $comment = new Comment();
                $commentMessage = file_get_contents($rootPath.DIRECTORY_SEPARATOR.$commentsData['message']);
                $comment
                    ->setMessage($commentMessage)
                    ->setAuthor($this->retrieveUser($commentsData['author'], $owner))
                    ->setCreationDate(new \DateTime($postsData['creation_date']))
                    ->setUpdateDate(new \DateTime($postsData['modification_date']))
                    ->setPublicationDate(new \DateTime($postsData['publication_date']))
                    ->setStatus($commentsData['status'])
                ;
                if (isset($commentsData['reported'])) {
                    $comment->setReported($commentsData['reported']);
                }

                $this->objectManager->persist($comment);
                $comments->add($comment);
            }

            $postContent = file_get_contents($rootPath.DIRECTORY_SEPARATOR.$postsData['content']);

            $post
                ->setTitle($postsData['title'])
                ->setContent($postContent)
                ->setAuthor($this->retrieveUser($postsData['author'], $owner))
                ->setCreationDate(new \DateTime($postsData['creation_date']))
                ->setModificationDate(new \DateTime($postsData['modification_date']))
                ->setPublicationDate(new \DateTime($postsData['publication_date']))
                ->setComments($comments)
                ->setStatus($postsData['status'])
            ;

            if (isset($postsData['pinned'])) {
                $post->setPinned($postsData['pinned']);
            }

            $posts->add($post);
        }

        $blog->setPosts($posts);

        return $blog;
    }