Move up page position in menu

@param number $pageId
@param string $menuName
@return
432220
public function upAction($pageId, $menuName)
    {
        $pageMenuRepo = $this->getDoctrine()->getRepository('FulgurioLightCMSBundle:PageMenu');
        $pageMenu = $pageMenuRepo->findOneBy(array('page' => $pageId, 'label' => $menuName));
        $position = $pageMenu->getPosition();
        if ($position > 1)
        {
            $pageMenuRepo->downMenuPagesPosition($menuName, $position - 1, $position);
            $pageMenu->setPosition($position - 1);
            $em = $this->getDoctrine()->getManager();
            $em->persist($pageMenu);
            $em->flush();
            $this->get('session')->getFlashBag()->add(
                    'notice',
                    $this->get('translator')->trans('fulgurio.lightcms.menus.moving_success_msg', array(), 'admin'));
        }
        return $this->redirect($this->generateUrl('AdminMenus'));
    }
975132
public function init($pageId, array $typoScriptSetup = [])
    {
        $this->setLanguageService($GLOBALS['LANG']);
        $pageId = (strpos($pageId, 'NEW') === 0) ? 0 : (int)$pageId;
        if ((int)$pageId < 0) {
            $pageId = Helper::getInstance()->getPidFromUid($pageId);
        }
        $this->realPid = $pageId;
        $this->loadLayoutSetup($pageId);
        foreach ($this->layoutSetup as $key => $setup) {
            $columns = $this->getLayoutColumns($key);
            if ($columns['allowed'] || $columns['disallowed'] || $columns['maxitems']) {
                $this->layoutSetup[$key]['columns'] = $columns;
                unset($this->layoutSetup[$key]['columns']['allowed']);
                $this->layoutSetup[$key]['allowed'] = $columns['allowed'] ?: [];
                $this->layoutSetup[$key]['disallowed'] = $columns['disallowed'] ?: [];
                $this->layoutSetup[$key]['maxitems'] = $columns['maxitems'] ?: [];
            }
        }
        $this->setTypoScriptSetup($typoScriptSetup);
        return $this;
    }
163320
public function editAction($pageId)
    {
        $options = array(
            'pageId' => $pageId,
            'pageMetas' => $this->getPageMetas($pageId)
        );
        $page = $this->getPage($pageId);
        return $this->createPage(
                $page,
                $options,
                $models = $this->container->getParameter('fulgurio_light_cms.models')
        );
    }
82862
public function indexAction(Request $request, $menuid)
    {
        $menuRepo = $this->getDoctrine()->getManager()->getRepository(
            $this->container->getParameter('kunstmaan_menu.entity.menu.class')
        );

        /** @var BaseMenu $menu */
        $menu = $menuRepo->find($menuid);
        if ($menu->getLocale() != $request->getLocale()) {
            /** @var BaseMenu $translatedMenu */
            $translatedMenu = $menuRepo->findOneBy(['locale' => $request->getLocale(), 'name' => $menu->getName()]);
            $menuid = $translatedMenu->getId();
        }

        $configurator = $this->getAdminListConfigurator($request, $menuid);
        $itemRoute = function (EntityInterface $item) use ($menuid) {
            return array(
                'path' => 'kunstmaanmenubundle_admin_menuitem_move_up',
                'params' => array(
                    'menuid' => $menuid,
                    'item' => $item->getId(),
                ),
            );
        };
        $configurator->addItemAction(new SimpleItemAction($itemRoute, 'arrow-up', 'kuma_admin_list.action.move_up'));

        $itemRoute = function (EntityInterface $item) use ($menuid) {
            return array(
                'path' => 'kunstmaanmenubundle_admin_menuitem_move_down',
                'params' => array(
                    'menuid' => $menuid,
                    'item' => $item->getId(),
                ),
            );
        };
        $configurator->addItemAction(new SimpleItemAction($itemRoute, 'arrow-down', 'kuma_admin_list.action.move_down'));

        return parent::doIndexAction($configurator, $request);
    }
1194855
public function getSeoKeywordsByPageId($pageId)
    {
        $pageId = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', ''));
        $data = array();

        $seoKeywords = $pageId->getSeoKeywords($pageId);
        $data        = $seoKeywords;

        return $data;
    }
200325
protected function buildSitemap($rootPageId, $languageId)
    {
        if ($languageId !== null) {
            // Language lock enabled
            $rootPageLinkTemplate = 'sitemap-r%s-l%s-p###PAGE###.xml.gz';
            $sitemapIndexFileName = 'index-r%s-l%s.xml.gz';
            $sitemapPageFileName  = 'sitemap-r%s-l%s-p%s.xml.gz';
        } else {
            $rootPageLinkTemplate = 'sitemap-r%s-p###PAGE###.xml.gz';
            $sitemapIndexFileName = 'index-r%s.xml.gz';
            $sitemapPageFileName  = 'sitemap-r%s-p%3$s.xml.gz';
        }

        // Init builder
        $generator = $this->objectManager->get('Metaseo\\Metaseo\\Sitemap\\Generator\\XmlGenerator');
        $fileName  = sprintf($rootPageLinkTemplate, $rootPageId, $languageId);

        $generator->indexPathTemplate = $this->generateSitemapLinkTemplate($fileName);

        // Get list of pages
        $pageCount = $generator->pageCount();

        // Index
        $content  = $generator->sitemapIndex();
        $fileName = sprintf($sitemapIndexFileName, $rootPageId, $languageId);
        $this->writeToFile(PATH_site . '/' . $this->sitemapDir . '/' . $fileName, $content);

        // Page
        for ($i = 0; $i < $pageCount; $i++) {
            $content  = $generator->sitemap($i);
            $fileName = sprintf($sitemapPageFileName, $rootPageId, $languageId, $i);
            $this->writeToFile(PATH_site . '/' . $this->sitemapDir . '/' . $fileName, $content);
        }

        return true;
    }
223727
public function findPageById($pageId)
    {
        $this->makeCollectionPageSelect(true);
        $this->sql .= ' and p.id = ?';
        $this->bindValues[] = $pageId;

        return $this->findRow();
    }
163870
public static function getIsSiteManagedSite($pageId)
    {

        $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
        try {
            $site = $siteFinder->getSiteByPageId($pageId);
        } catch (SiteNotFoundException $e) {
            return false;
        }

        return $site instanceof Site;
    }
509389
public function deleteMenu($lang, $menuID)
    {
        // check if user has permissions to access this link
        if(!User::hasAccess('Menu', 'delete')) {
            return $this->noPermission();
        }

        $menu = Menu::find($menuID);
        if(!$menu) {
            return $this->response("Menu doesn't exist", 400);
        }

        if(!$menu->isPrimary) {
            $menuLinks = MenuLink::where('menuID', $menuID);
            $menuLinks->delete();
            $menu->delete();
            return $this->response("Menu deleted", 200, Menu::getPrimaryMenuID());
        }else{
            return $this->response("Primary menu can not be deleted", 400);
        }
    }
746791
public function newPlacementAction(Request $request, $newMenuItemId, $menuItemId)
    {
        $sibling = $request->get('sibling');

        /** @var MenuItemManager $menuItemManager */
        $menuItemManager = $this->get('networking_init_cms.menu_item_manager');
        $newMenuItem = $menuItemManager->find($newMenuItemId);
        $menuItem = $menuItemManager->find($menuItemId);

        if (!$newMenuItem || !$menuItem) {
            throw new NotFoundHttpException();
        }

        $data = [];
        try {
            if ($sibling) {
                $menuItemManager->persistAsNextSiblingOf($newMenuItem, $menuItem);
            } else {
                $menuItemManager->persistAsFirstChildOf($newMenuItem, $menuItem);
            }
            $this->getDoctrine()->getManager()->flush();
            $data = [
                'result' => 'ok',
                'objectId' => $this->admin->getNormalizedIdentifier($newMenuItem),
            ];

            return $this->renderJson($data);
        } catch (\Exception $e) {
            return $this->renderJson($data);
        }
    }
298928
public function setPage($pagenum)
    {
        if($pagenum > $this->getPages()) {
            $pagenum = $this->getPages();
        }
        if($pagenum < 1) {
            $pagenum = 1;
        }

        $this->pagenum = $pagenum;
        return $this;
    }
961526
public function cloneMenu(int $menuId, int $siteId, string $name): Tree
    {
        $source = $this->menuStorage->load($menuId);
        $values = [
            'title'       => $source->getTitle(),
            'description' => $source->getDescription(),
            'site_id'     => $siteId,
        ];
        $target = $this->menuStorage->create($name, $values);

        return $this->cloneTreeIn($target->getId(), $this->buildTree($menuId));
    }
605785
public function moveBlocksAction()
	{
		$this->isPostRequest();
		$this->checkLock();

		$pageRequest = $this->createPageRequest();

		$blockId = $this->getRequestInput()->get('block_id');

		$block = $this->getEntityManager()
				->find(Block::CN(), $blockId);

		if ($block === null) {
			throw new CmsException(null, sprintf('Block with ID [%s] not found.', $blockId));
		}

		$targetPlaceHolderName = $this->getRequestParameter('place_holder_id');

		$targetPlaceHolder = $pageRequest->getPlaceHolderSet()
				->getFinalPlaceHolders()
				->offsetGet($targetPlaceHolderName);

		if ($targetPlaceHolder === null) {
			throw new \InvalidArgumentException(sprintf(
					'Placeholder [%s] not found in placeholders set.',
					$targetPlaceHolderName
			));
		}

		$currentPlaceHolder = $block->getPlaceHolder();

		if ($currentPlaceHolder === $targetPlaceHolder) {
			// JS error or data spoofing
			throw new \LogicException('Current and new placeholders are the same.');
		}

		$currentPlaceHolder->removeBlock($block);

		$targetPlaceHolder->addBlockLast($block);

		// @TODO: not quite sure that block will exists in collection already.
		//		should be rewrited.
		$blockSet = $pageRequest->getBlockSet()
				->getPlaceHolderBlockSet($targetPlaceHolder);

		$blockPositionMap = array_values($this->getRequestParameter('order', array()));

		if ($blockSet->count() !== count($blockPositionMap)) {
			// JS error or data spoofing
			throw new \UnexpectedValueException('Ordered elements and actual blocks count does not match.');
		}

		foreach ($blockPositionMap as $position => $id) {

			$block = $blockSet->findById($id);

			if ($block === null) {
				throw new \UnexpectedValueException(sprintf('Block [%s] not found.'));
			}

			$block->setPosition($position);
		}

		$this->getEntityManager()
				->flush();

		return new SupraJsonResponse();
	}
1344361
public static function parentID($menuLinkID)
    {
        $parentIDs = [];
        while($menuLinkID != null){
            $parentObj = MenuLink::all()->where('menuLinkID', $menuLinkID)->first();
            if ($parentObj) {
                $menuLinkID = $parentObj->parent;
                if ($menuLinkID) {
                    $parentIDs[] = $menuLinkID;
                }
            }
            if ($parentObj || !$menuLinkID) {
                $menuLinkID = null;
            }
        }
        return $parentIDs;
    }
565896
public function forward(PageDocument $page, $templateName)
    {
        $request = $this->requestStack->getCurrentRequest();
        $subRequest = $request->duplicate([], null, [
            '_controller'     => self::GLOBAL_CONTROLLER_ACTION,
            'contentDocument' => $page,
            'contentTemplate' => $templateName
        ]);

        return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    }
34453
public function getPageLayout($pageId, $pageThemeId = null)
    {
        $sections = $templateSections = [];
        $error    = '';
        $details  = [];

        /** @var $pageModel \PageBuilder\Model\PageModel */
        $pageModel = $this->getServiceLocator()->get('pagebuilder\model\page');

        /** @var $themeModel \PageBuilder\Model\BaseModel */
        $themeModel = $this->getServiceLocator()->get('pagebuilder\model\theme');

        /** @var $templateModel \PageBuilder\Model\BaseModel */
        $templateModel = $this->getServiceLocator()->get('pagebuilder\model\template');

        /** @var $page \PageBuilder\Entity\Page */
        if ($page = $pageModel->getRepository()->find($pageId)) {

            $details = [
                'id'          => $page->getId(),
                'title'       => $page->getTitle(),
                'description' => $page->getDescription(),
                'template'    => $page->getTemplate() ? $page->getTemplate()->getTitle() : '',
                'layout'      => '',
                'pageTheme'   => '',
                'themeId'     => '',
                'layoutType'  => 'Custom Layout',
                'parent'      => $page->getParent() ? $page->getParent()->getTitle() : '',

            ];
        }
        $themeId = $pageTheme = null;
        if ($pageThemeId) {
            /** @var $pageThemeModel \PageBuilder\Model\BaseModel */
            $pageThemeModel = $this->getServiceLocator()->get('pagebuilder\model\pageTheme');
            $pageTheme      = $pageThemeModel->findObject($pageThemeId);
            $themeId        = $pageTheme->getId();
        }

        if ($themeId and $pageTheme) {
            $details['themeId'] = $themeId;

            $details['layout']    = $pageTheme->getLayout();
            $details['pageTheme'] = $pageTheme->getId();

            /** @var $temp \PageBuilder\Entity\Template */
            if ($temp = $page->getTemplate()) {
                $sections = $temp->getTemplateSections()->toArray();
            } elseif ($temp = $page->getParent()->getTemplate()) {
                $sections = $temp->getTemplateSections()->toArray();
            }
        }
        /** @var $section \PageBuilder\Entity\Join\TemplateSection */
        foreach ($sections as $section) {
            $slug                    = $section->getSectionId()->getSlug();
            $templateSections[$slug] = [
                'title'  => $section->getSectionId()->getTitle(),
                'status' => $section->getIsActive() ? 1 : 0,
                'class'  => $section->getIsActive() ? '' : 'in-active',
            ];
        }

        if ($themeData = $themeModel->getRepository()->findAll()) {
            /** @var $theme \PageBuilder\Entity\Theme */
            foreach ($themeData as $theme) {
                $details['themes'][$theme->getId()] = $theme->toArray();
            }
        } else {
            $details['themes'] = [];
        }

        /** @var $templateModel \PageBuilder\Model\TemplateModel */
        $templates  = $templateModel->listTemplates();
        $components = $this->getServiceLocator()->get('pagebuilder\model\component')->listItemsByTitle();

        /** @var $widgetUtil \PageBuilder\Util\Widget */
        $widgetUtil = $this->getServiceLocator()->get('util\widget');

        $widgetList = $widgetUtil->getWidgetList();
        $urlHelper  = $this->getServiceLocator()->get('ViewHelperManager')->get('url');

        $return = [
            'error'     => $error,
            'page'      => $details,
            'editUrl'   => $pageThemeId
                ? $urlHelper('builder\theme', ['id' => $pageThemeId])
                : $urlHelper(
                    'builder', ['id' => $pageId]
                ),
            'sections'  => $templateSections,
            'title'     => 'Layout Manager - ' . ($page ? $page->getTitle() : ''),
            'widgets'   => [
                'title' => 'Widgets',
                'items' => $widgetUtil->getRegistry(),
                'total' => count($widgetUtil->getRegistry()),
                'list'  => $widgetList,
                'id'    => PageBuilder::LAYOUT_WIDGET,
            ],
            'assets'    => [
                PageBuilder::LAYOUT_USER_DEFINED => [
                    'title' => 'User Defined',
                    'items' => $components,
                ],
            ],
            'templates' => [
                'title' => 'Templates',
                'items' => $templates,
            ],
            'tags'      => $this->_getTaglist(),
        ];

        return $return;
    }
592035
public static function copyBlocks($fromPageId, $toPageId)
    {
        $pageBlocks = NavItemPageBlockItem::find()->where(['nav_item_page_id' => $fromPageId])->asArray(true)->all();
        
        $idLink = [];
        foreach ($pageBlocks as $block) {
            $blockItem = new NavItemPageBlockItem();
            $blockItem->attributes = $block;
            $blockItem->nav_item_page_id = $toPageId;
            if ($blockItem->insert()) {
                $idLink[$block['id']] = $blockItem->id;
            }
        }
        
        // as blocks with subblocks have the previous block id stored in prev_id those values must be replaced from the old prev_id
        // with the new prev_id
        $newPageBlocks = NavItemPageBlockItem::find()->where(['nav_item_page_id' => $toPageId])->asArray(true)->all();
        foreach ($newPageBlocks as $block) {
            if ($block['prev_id'] && isset($idLink[$block['prev_id']])) {
                // update the given blocks' prev_id
                NavItemPageBlockItem::updateAll(['prev_id' => $idLink[$block['prev_id']]], ['id' => $block['id']]);
            }
        }
        
        return true;
    }