Check if the page part is insertable into the current page.

@throws \LogicException
199639
protected function validateParentPage()
    {
        $request = $this->requestStack->getMasterRequest();

        // the node which the pagepart belongs to
        if ($request->query->has('pageid') && $request->query->has('pageclassname')) {
            $repo = $this->doctrine->getManager()->getRepository('KunstmaanNodeBundle:Node');
            $node = $repo->getNodeForIdAndEntityname(
              $request->query->get('pageid'),
              $request->query->get('pageclassname')
            );

            $pageReflection = new \ReflectionClass($node->getRefEntityName());

            // if the current page implements the interface, then it is forbidden to insert anything beneath
            if ($pageReflection->implementsInterface(InsertablePageInterface::class)) {
                $currentContext = $this->requestStack->getMasterRequest()->get('context');
                $page = $pageReflection->newInstanceWithoutConstructor();

                // get pagepart configurations for the current page
                $pagePartConfigs = $this->pagePartConfigReader->getPagePartAdminConfigurators($page);

                foreach ($pagePartConfigs as $config) {
                    if ($config->getContext() === $currentContext) {
                        foreach ($config->getPossiblePagePartTypes() as $pagePartType) {
                            if ($pagePartType['class'] === InsertPagePagePart::class) {
                                throw new \LogicException(
                                  sprintf(
                                    'The %s page must not allow %s as possible page part, because it implements %s! You must modify the "%s" context.',
                                    $pageReflection->getName(),
                                    InsertPagePagePart::class,
                                    InsertablePageInterface::class,
                                    $currentContext
                                  ));
                            }
                        }
                    }
                }
            }
        }
    }
962921
public function renderContent()
    {
        if (is_object($this->content) && !method_exists($this->content, '__toString')) {
            throw new \LogicException('Cannot render content: it is an object without __toString method!');
        }

        if (is_array($this->content)) {
            throw new \LogicException('Cannot render content: it is an array!');
        }

        return (string) $this->content;
    }
1241791
protected function submitEditPage()
    {
        if ($this->isPosted('delete')) {
            $this->deletePage();
        } else if ($this->isPosted('save') && $this->validateEditPage()) {
            $this->deleteImagesPage();
            if (isset($this->data_page['page_id'])) {
                $this->updatePage();
            } else {
                $this->addPage();
            }
        }
    }
672017
private function checkBoundary()
    {
        if($this->page->current > $this->page->total_pages) {

            $queryLink = !empty($this->page->currentUri) ? '&' : '?';
            $redirectUrl = substr($this->currentUri, 1) . $queryLink . 'page=' . $this->page->total_pages;

            $this->di->get('response')->redirect($redirectUrl);
        }
    }
547666
public function insertBlockAction()
	{
		$this->isPostRequest();
		$this->checkLock();

		$pageRequest = $this->createPageRequest();

		$blockComponentName = $this->getRequestParameter('type');

		// Generate block according the page localization type provided
		$block = Block::factory($this->getPageLocalization());
		$block->setComponentName($blockComponentName);

		$class = $block->getComponentClass();

		$blockConfiguration = $this->getBlockCollection()
				->getConfiguration($class);

		// logic/code issue
		if (! $blockConfiguration->isInsertable()) {
			throw new CmsException(null, 'This block cannot be added.');
		}

		// deny adding if block is defined as unique
		// and page block set already contains it.
		if ($blockConfiguration->isUnique()) {

			foreach ($pageRequest->getBlockSet() as $existingBlock) {

				if ($existingBlock->getComponentClass() === $class) {
					throw new CmsException(
							null,
							sprinf(
									'Only one instance of "%s" block can be added on the page.',
									$blockConfiguration->getTitle()
							)
					);
				}
			}
		}

		$placeHolderName = $this->getRequestParameter('placeholder_id');

		$placeHolder = $pageRequest->getPlaceHolderSet()
				->getFinalPlaceHolders()
				->offsetGet($placeHolderName);

		if ($placeHolder === null) {
			throw new \InvalidArgumentException(sprintf(
					'Missing placeholder [%s] in place holder set.',
					$placeHolderName
			));
		}

		$insertBeforeTargetId = $this->getRequestInput()->get('reference_id');

		if (! empty($insertBeforeTargetId)) {

			$insertBeforeTarget = null;
			
			foreach ($placeHolder->getBlocks() as $existingBlock) {
				if ($existingBlock->getId() === $insertBeforeTargetId) {
					$insertBeforeTarget = $existingBlock;
					break;
				}
			}

			if ($insertBeforeTarget === null) {
				throw new \InvalidArgumentException(sprintf(
						'Blocks collection item [%s] not found.',
						$insertBeforeTargetId
				));
			}

			$placeHolder->addBlockBefore($insertBeforeTarget, $block);

		} else {
			$placeHolder->addBlockLast($block);
		}

		$entityManager = $this->getEntityManager();

		$entityManager->persist($block);

		$entityManager->flush();

		return new SupraJsonResponse($this->getBlockData($block, true));
	}
81713
public function includeAceEditor()
    {
        if ($this->editorIncluded) {
            return;
        }

        if (!$this->environment->hasExtension(AssetExtension::class)) {
            throw new \LogicException('"asset" extension is mandatory if you don\'t include Ace editor by yourself.');
        }

        if (!$this->editorIncluded) {
            foreach (['ace', 'ext-language_tools'] as $file) {
                /** @var AssetExtension $extension */
                $extension = $this->environment->getExtension(AssetExtension::class);
                $jsPath = $extension->getAssetUrl($this->basePath.'/'.$this->mode.'/'.$file.'.js');

                printf('<script src="%s" charset="utf-8" type="text/javascript"></script>', $jsPath);
            }
            $this->editorIncluded = true;
        }
    }
517252
protected function _setPageFooter()
    {
        if (!count($this->_subFOOTER)) {
            return false;
        }

        if (in_array($this->pdf->getPage(), $this->_hideFooter)) {
            return false;
        }

        $oldParsePos = $this->_parsePos;
        $oldParseCode = $this->parsingHtml->code;

        $this->_parsePos = 0;
        $this->parsingHtml->code = $this->_subFOOTER;
        $this->_isInFooter = true;
        $this->_makeHTMLcode();
        $this->_isInFooter = false;

        $this->_parsePos = $oldParsePos;
        $this->parsingHtml->code = $oldParseCode;
    }
935012
protected function CanCreateIn()
    {
        return self::Guard()->GrantAddContentToPageArea($this->page, $this->area)
            ->ToBool() && self::Guard()->Allow(BackendAction::UseIt(), new ModuleForm());
    }
679971
def check(self, action, page=None, lang=None, method=None):
        """"""
        if self.user.is_superuser:
            return True

        if action == 'change':
            return self.has_change_permission(page, lang, method)

        if action == 'delete':
            if not self.delete_page():
                return False
            return True
        if action == 'add':
            if not self.add_page():
                return False
            return True
        if action == 'freeze':
            perm = self.user.has_perm('pages.can_freeze')
            if perm:
                return True
            return False
        if action == 'publish':
            perm = self.user.has_perm('pages.can_publish')
            if perm:
                return True
            return False

        return False
1289173
protected function insert()
    {
        if ($this->isDirty()) {
            $sql = 'INSERT INTO '.$this->getTableName().'  SET ';
            $data = [];
            $params = [];

            $pk_name = $this->getPkName();

            foreach ((new \ReflectionObject($this))->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
                if ($this->{$property->getName()}) {
                    if ($this->{$property->getName()} instanceof Expression) {
                        $data[] = "`{$property->getName()}` = ".$this->{$property->getName()}->toSql();
                    } else {
                        $data[] = "`{$property->getName()}` = :{$property->getName()}";
                        $params[":{$property->getName()}"] = $this->{$property->getName()};
                    }
                }
            }

            $sql .= implode(',', $data);

            $stmt = $this->getDB()->prepare($sql);
            $stmt->execute($params);
            $last_insert_id = $this->getDB()->lastInsertId();

            if (is_array($pk_name)) {
                /*
                 * @TODO: Composite PK
                 */
            } else {
                $this->{$pk_name} = $last_insert_id;
            }

            $this->setDirty(false);
            $stmt->closeCursor();
            $this->_is_new = false;
        }

        return true;
    }
205016
private function addHtmlElementIfMissing(): bool
    {
        if ($this->getElementsByTagName('html')->length === 0) {
            if (!isset(self::$newObjectsCache['htmlelement'])) {
                self::$newObjectsCache['htmlelement'] = new \DOMElement('html');
            }
            $this->appendChild(clone(self::$newObjectsCache['htmlelement']));
            return true;
        }
        return false;
    }
588336
public function accept()
    {
        $accepted = (bool) $this->isAccepted();
        if ($accepted === false && $this->current() instanceof PageInterface) {
            $parent = $this->current()->getParent();
            if (!empty($parent)) {
                $parent->removePage($this->current());
            }
        }

        return $accepted;
    }
86926
protected function validatePage()
    {
        $id = $this->getUpdatingId();

        if ($id === false) {
            return null;
        }

        $data = $this->page->get($id);

        if (empty($data)) {
            $this->setErrorUnavailable('update', $this->translation->text('Page'));
            return false;
        }

        $this->setUpdating($data);
        return true;
    }
12017
private function checkPageHasImages() {

        $html = $this->getPageContent();

        // for newly created page
        if ($html == '') {
            return false;
        }

        $dom = $this->createDOMDocumentFromHTML($html);

        $elements = $dom->getElementsByTagName('img');
        return ($elements->length) ? true : false;

    }
902917
public function isEditing($mode = null)
    {
        $page_mode = $this->virtual_page->isActive();

        // Requested edit, but not allowed
        if ($page_mode == 'edit' && !$this->allow_edit) {
            throw $this->exception('Editing is not allowed');
        }

        // Requested add but not allowed
        if ($page_mode == 'add' && !$this->allow_add) {
            throw $this->exception('Adding is not allowed');
        }

        // Request matched argument exactly
        if (!is_null($mode)) {
            return $mode === $page_mode;
        }

        // Argument was blank, then edit/add is OK
        return (boolean) $page_mode;
    }
677501
protected function isPageExcludedFromSitemap(Page $page)
    {
        $ak = $this->getExcludeFromSiteMapAttributeKey();
        if ($ak === null) {
            $result = false;
        } else {
            $result = (bool) $page->getAttribute($ak);
        }

        return $result;
    }
749066
protected function checkForMainOffsetOrLimit($sql)
    {
        if ("" !== $this->stripQueryToUnnestedKeyword($sql, $unnested_keyword = 'LIMIT')) {
            throw new \LogicException("Query cannot contain an unnested LIMIT when trying to paginate");
        }

        if ("" !== $this->stripQueryToUnnestedKeyword($sql, $unnested_keyword = 'OFFSET')) {
            throw new \LogicException("Query cannot contain an unnested OFFSET when trying to paginate");
        }

        return true;
    }