This function creates the Page Property Form and sends it back

@param int $idPage
@param bool $isNew
@return \Zend\Form\Form
969500
public function getSeoPageForm($idPage)
	{
		$pathAppConfigForm = self::PageSeoAppConfigPath;
		 
		/**
		 * Get the config for this form
		 */
		$melisMelisCoreConfig = $this->serviceLocator->get('MelisCoreConfig');
		$appConfigForm = $melisMelisCoreConfig->getItem($pathAppConfigForm, $idPage . '_');
		
		
		/**
		 * Generate the form through factory and change ElementManager to
		 * have access to our custom Melis Elements
		 * Bind with datas
		 */
		$factory = new \Zend\Form\Factory();
		$formElements = $this->serviceLocator->get('FormElementManager');
		$factory->setFormElementManager($formElements);
		$appConfigForm['attributes']['action'] .= '?idPage=' . $idPage;
		$seoForm = $factory->createForm($appConfigForm);
	
		return $seoForm;
	}
790370
public function action($page, $id, $action)
    {
        $this->authorize($action, $eloquent = app('scaffold.model'));

        $response = app('scaffold.actions')->exec('action::' . $action, [$eloquent]);

        if ($response instanceof Response || $response instanceof Renderable) {
            return $response;
        }

        return back()->with(
            'messages',
            [trans('administrator::messages.action_success')]
        );
    }
623119
public function setModel(array $data = [], $isNew = true)
    {
        $this->data = $data;

        $this->validator = new \Illuminate\Validation\Validator(
            $this->translator,
            $this->data,
            $this->getRules($isNew),
            $this->getMessages()
        );

        $this->validator->setPresenceVerifier($this->presenceVerifier);

        $this->sometimes($this->validator, $isNew);

        return $this;
    }
966909
protected function handleWritePage($request, $id = null)
    {
        $page = $id ? $this->getPage($id) : null;

        $form = $this->formFactory->createNamed(null, 'sonata_page_api_form_page', $page, [
            'csrf_protection' => false,
        ]);

        $form->handleRequest($request);

        if ($form->isValid()) {
            $page = $form->getData();
            $this->pageManager->save($page);

            return $this->serializeContext($page, ['sonata_api_read']);
        }

        return $form;
    }
55367
public function updateTitleAndDescription($idPage, $contentGenerated)
	{
		$newContent = $contentGenerated;
		
		// Get the page title
		$melisPage = $this->serviceLocator->get('MelisEnginePage');
		$datasPage = $melisPage->getDatasPage($idPage, 'published');
		if (!empty($datasPage))
		{
			$pageTree = $datasPage->getMelisPageTree();
			if (!empty($pageTree))
			{
				/**
				 * Get SEO for this page
				 */
				$melisTablePageSeo = $this->serviceLocator->get('MelisEngineTablePageSeo');
				$datasPageSeo = $melisTablePageSeo->getEntryById($idPage);
				/**
				 * Description tag
				 */
				if (!empty($datasPageSeo = $datasPageSeo->current()))
				{
					if (!empty($datasPageSeo)) {
						$descriptionPage = addslashes($datasPageSeo->pseo_meta_description);
                        $descriptionPage = str_replace("\'", "'", $descriptionPage);

                        $titlePage = addslashes($datasPageSeo->pseo_meta_title);
                        $titlePage = str_replace("\'", "'", $titlePage);
						if ($descriptionPage != '') {
                            $descriptionTag = "\n\t<meta name=\"description\" content=\"$descriptionPage\" />\n";
                            $titleTag = "<title>$titlePage</title>";
                            $descriptionRegex = '/(<meta[^>]*name=[\"\']description[\"\'][^>]*content=[\"\'](.*?)[\"\'][^>]*>)/i';
                            $titleReg = '/\<title\>+(.*?)+\<\/title>/';

                            preg_match($descriptionRegex, $contentGenerated, $descriptions);
                            preg_match($titleReg, $contentGenerated, $titles);
                            if (!empty($descriptions)) {
                                // Replace existing title in source with the page name
                                $newContent = preg_replace($descriptionRegex, $descriptionTag, $contentGenerated,1);
                            } else {
                                // Title doesn't exist, look for head tag to add
                                // if no head tag, then nothing will happen
                                $headRegex = '/(<head[^>]*>)/im';
                                $newContent = preg_replace($headRegex, "$1$descriptionTag", $contentGenerated,1);
                            }

                            if (!empty($titles)) {
                                // Replace existing title in source with the page name
                                $newContent = preg_replace($titleReg, $titleTag, $newContent);
                            } else {
                                // Title doesn't exist, look for head tag to add
                                // if no head tag, then nothing will happen
                                $headRegex = '/(<head[^>]*>)/im';
                                $newContent = preg_replace($headRegex, "$1$titleTag", $newContent,1);
                            }

                            $contentGenerated = $newContent;

                        }
					}
                    /**
                     * Canonical Tag
                     */
                    $canonicalUrl = addslashes($datasPageSeo->pseo_canonical);
                    $canonicalUrl = str_replace("\'", "'", $canonicalUrl);
                    if ($canonicalUrl != '') {
                        $canonicalUrlTag = "\n\t<link rel=\"canonical\" href=\"$canonicalUrl\" />\n";
                        $canonicalRegex = '/(<link[^>]*rel=[\"\']canonical[\"\'][^>]*content=[\"\'](.*?)[\"\'][^>]*>)/i';
                        preg_match($canonicalRegex, $contentGenerated, $canonicalFound);
                        if(!empty($canonicalFound)){
                            $newContent = preg_replace($canonicalRegex, $canonicalUrlTag, $contentGenerated,1);
                        }else {
                            $headRegex = '/(<head[^>]*>)/im';
                            $newContent = preg_replace($headRegex, "$1$canonicalUrlTag", $contentGenerated,1);
                        }
                        $contentGenerated = $newContent;
                    }else{
                        /**
                         * @var MelisTreeService
                         */
                        $pageService = $this->serviceLocator->get('MelisEngineTree');
                        $pageUrl = $pageService->getPageLink($idPage);
                        $canonicalUrlTag = "\n\t<link rel=\"canonical\" href=\"$pageUrl\" />\n";
                        $canonicalRegex = '/(<link[^>]*rel=[\"\']canonical[\"\'][^>]*content=[\"\'](.*?)[\"\'][^>]*>)/i';
                        preg_match($canonicalRegex, $contentGenerated, $canonicalFound);
                        if(!empty($canonicalFound)){
                            $newContent = preg_replace($canonicalRegex, $canonicalUrlTag, $contentGenerated ,1);
                        }else {
                            $headRegex = '/(<head[^>]*>)/im';
                            $newContent = preg_replace($headRegex, "$1$canonicalUrlTag", $contentGenerated,1);
                        }
                        $contentGenerated = $newContent;
                    }
				}

				/**
				 * Title tag
				 */
				$titlePage = $pageTree->page_name;
				if (!empty($datasPageSeo) && !empty($datasPageSeo->pseo_meta_title))
					$titlePage = $datasPageSeo->pseo_meta_title;
				
				$titleRegex = '/(<title[^>]*>)([^<]+)(<\/title>)/im';
				preg_match($titleRegex, $contentGenerated, $titles);
				if (!empty($titles))
				{
					// Replace existing title in source with the page name
					$newContent = preg_replace($titleRegex, "$1$titlePage$3", $contentGenerated,1);
				}
				else
				{
					// Title doesn't exist, look for head tag to add
					// if no head tag, then nothing will happen
					$headRegex = '/(<head[^>]*>)/im';
					$titleTag = "\n<title>$titlePage</title>\n";
					$newContent = preg_replace($headRegex, "$1$titleTag", $contentGenerated, 1);
				}
				
			}
		}
		
		return $newContent;
	}
1109441
public function getPageChildren($idPage, $publishedOnly = 0)
	{
	    if (empty($idPage))
	        return null;
	    
        // Retrieve cache version if front mode to avoid multiple calls
        /* $cacheKey = 'getPageChildren_' . $idPage . '_' . $publishedOnly;
        $cacheConfig = 'engine_page_services';
        $melisEngineCacheSystem = $this->serviceLocator->get('MelisEngineCacheSystem');
        $results = $melisEngineCacheSystem->getCacheByKey($cacheKey, $cacheConfig);
        if (!empty($results)) return $results; */
	         
		$tablePageTree = $this->getServiceLocator()->get('MelisEngineTablePageTree');
		$datasPage = $tablePageTree->getPageChildrenByidPage($idPage, $publishedOnly);

		// Save cache key
		/* $melisEngineCacheSystem->setCacheByKey($cacheKey, $cacheConfig, $datasPage); */
		
		return $datasPage;
	}
508082
public function save($isNewRecord)
    {
        if ($this->validate()) {
            $user = $this->user;
            $data = [];
            $fn = $user->formName();
            if ($isNewRecord) {
                $data[$fn]['username']    = $this->username;
            }
            $data[$fn]['email']           = $this->email;
            $data[$fn]['password']        = $this->password_new;
            $data[$fn]['change_auth_key'] = $this->change_auth_key;

            $loaded = $user->load($data);
            if ($isNewRecord) {
                $user->scenario = $user::SCENARIO_CREATE;
                $user->status = $user::STATUS_REGISTERED;
                $saved = $user->insert();
            } else {
                $saved = $user->update();
            }
            if ($loaded && $saved) {
                $this->auth_key = $user->auth_key;
                return $saved;
            } else {
                $this->addErrors($user->errors);
            }
        }
        return false;
    }
989716
public function addPage($id = "", $header = "", $meta = array())
    {
        $objPage = new Page($id, $header, $meta);
        $this->__elements->addObject($objPage);

        if ($this->__elements->count() == 1) {
            // Add unique id field.
            $this->addHiddenField("vf__uniqueid", ValidForm::VFORM_STRING, array(
                "default" => $this->getUniqueId()
            ));
        }

        $this->__pagecount ++;

        return $objPage;
    }
339899
protected function saving($name, $userId, $value = null, $isNew = true)
    {
        $meta = $this->getModel()->search($name, $userId)->first();

        if (is_null($value) || $value === ':to-be-deleted:') {
            !is_null($meta) && $meta->delete();
            return;
        }

        if (true === $isNew && is_null($meta)) {
            $meta = $this->getModel();

            $meta->name    = $name;
            $meta->user_id = $userId;
        }

        $meta->value = serialize($value);
        $meta->save();
    }
1304378
public function getEditForm($id = null, $fields = null)
    {
        if (!$id) {
            $id = $this->currentPageID();
        }

        // Check record exists
        $record = $this->getRecord($id);
        if (!$record) {
            return $this->EmptyForm();
        }

        // Check if this record is viewable
        if ($record && !$record->canView()) {
            $response = Security::permissionFailure($this);
            $this->setResponse($response);
            return null;
        }

        $fields = $fields ?: $record->getCMSFields();
        if (!$fields) {
            throw new LogicException(
                "getCMSFields() returned null  - it should return a FieldList object.
                Perhaps you forgot to put a return statement at the end of your method?"
            );
        }

        // Add hidden fields which are required for saving the record
        // and loading the UI state
        if (!$fields->dataFieldByName('ClassName')) {
            $fields->push(new HiddenField('ClassName'));
        }

        $tree_class = $this->config()->get('tree_class');
        if ($tree_class::has_extension(Hierarchy::class)
            && !$fields->dataFieldByName('ParentID')
        ) {
            $fields->push(new HiddenField('ParentID'));
        }

        // Added in-line to the form, but plucked into different view by frontend scripts.
        if ($record instanceof CMSPreviewable) {
            /** @skipUpgrade */
            $navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator());
            $navField->setAllowHTML(true);
            $fields->push($navField);
        }

        if ($record->hasMethod('getAllCMSActions')) {
            $actions = $record->getAllCMSActions();
        } else {
            $actions = $record->getCMSActions();
            // add default actions if none are defined
            if (!$actions || !$actions->count()) {
                if ($record->hasMethod('canEdit') && $record->canEdit()) {
                    $actions->push(
                        FormAction::create('save', _t('SilverStripe\\CMS\\Controllers\\CMSMain.SAVE', 'Save'))
                            ->addExtraClass('btn btn-primary')
                            ->addExtraClass('font-icon-add-circle')
                    );
                }
                if ($record->hasMethod('canDelete') && $record->canDelete()) {
                    $actions->push(
                        FormAction::create('delete', _t('SilverStripe\\Admin\\ModelAdmin.DELETE', 'Delete'))
                            ->addExtraClass('btn btn-secondary')
                    );
                }
            }
        }

        $negotiator = $this->getResponseNegotiator();
        $form = Form::create(
            $this,
            "EditForm",
            $fields,
            $actions
        )->setHTMLID('Form_EditForm');
        $form->addExtraClass('cms-edit-form');
        $form->loadDataFrom($record);
        $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
        $form->setAttribute('data-pjax-fragment', 'CurrentForm');
        $form->setValidationResponseCallback(function (ValidationResult $errors) use ($negotiator, $form) {
            $request = $this->getRequest();
            if ($request->isAjax() && $negotiator) {
                $result = $form->forTemplate();

                return $negotiator->respond($request, array(
                    'CurrentForm' => function () use ($result) {
                        return $result;
                    }
                ));
            }
            return null;
        });

        // Announce the capability so the frontend can decide whether to allow preview or not.
        if ($record instanceof CMSPreviewable) {
            $form->addExtraClass('cms-previewable');
        }
        $form->addExtraClass('fill-height');

        // Add a default or custom validator.
        if ($record->hasMethod('getCMSValidator')) {
            $validator = $record->getCMSValidator();
            // The clientside (mainly LeftAndMain*.js) rely on ajax responses
            // which can be evaluated as javascript, hence we need
            // to override any global changes to the validation handler.
            if ($validator) {
                $form->setValidator($validator);
            }
        } else {
            $form->unsetValidator();
        }

        // Check if this form is readonly
        if (!$record->canEdit()) {
            $readonlyFields = $form->Fields()->makeReadonly();
            $form->setFields($readonlyFields);
        }
        return $form;
    }
408155
protected function saving($name, $value = null, $isNew = true)
    {
        DB::transaction(function() use ($name, $value, $isNew) {
            $category = $this->getModel()->search($name)->first();

            if (is_null($value) || $value === ':to-be-deleted:') {
                !is_null($category) && $category->delete();
                return;
            }

            if (true === $isNew && is_null($category)) {
                $category       = $this->getModel();
                $category->name = $name;
            }
            $category->save();

            /**
             * saving group
             */
            $group = $category->group()->where('name', $value)->first();
            if (is_null($group)) {
                $group = $category->group()->getModel()->newInstance();
            }
            $group->fill([
                'category_id' => $category->id,
                'name'        => $value
            ]);
            $group->save();
        });
        return true;
    }
517376
protected function createComponentPageAddModal() : object
    {
        $control = $this->IPage_AddModal->create();

        $control->onOpen[] = function () use ($control)
        {
            $control->redrawControl('pageAddForm');
        };

        return $control;
    }
1300480
public function addPage(PageInterface $page, $route = null)
    {
        if (!isset($this->instances[$page->path()])) {
            $this->instances[$page->path()] = $page;
        }
        $route = $page->route($route);
        if ($page->parent()) {
            $this->children[$page->parent()->path()][$page->path()] = ['slug' => $page->slug()];
        }
        $this->routes[$route] = $page->path();

        $this->grav->fireEvent('onPageProcessed', new Event(['page' => $page]));
    }
387469
protected function createEditForm(ContentTypePage $page)
    {
        $channel = $page->getChannel();

        $form = $this->createForm(
            'integrated_page_content_type_page',
            $page,
            [
                'method' => 'PUT',
                'theme'  => $this->getTheme($channel),
                'controller' => $this->get($page->getControllerService()),
            ]
        );

        $form->add('submit', 'submit', ['label' => 'Save']);

        return $form;
    }
486038
private function AttachContainerContent($isNew)
    {
        $provider = new ContainerContentTreeProvider($this->Container());
        $tree = new TreeBuilder($provider);
        $containerContent = $this->Content()->GetContainerContent();
        if (!$containerContent) {
            $containerContent = new ContainerContent();
            $containerContent->SetContainer($this->Container());
            $provider->AttachContent($containerContent, $this->Content());
        }
        if ($isNew) {
            $tree->Insert($containerContent, $this->ParentItem(), $this->PreviousItem());
        }
    }
1113800
public function actionIndex($page = 1, $id = 0)
    {
        $searchModel = new NewsSearch();
        $params = Yii::$app->request->queryParams;
        if (!Yii::$app->user->can('roleNewsModerator') && Yii::$app->user->can('roleNewsAuthor')) {
            $params[$searchModel->formName()]['owner_id'] = Yii::$app->user->id;
        }//var_dump($params);
        $dataProvider = $searchModel->search($params);

        $pager = $dataProvider->getPagination();
        $pager->pageSize = $this->module->params['pageSizeAdmin'];
        $pager->totalCount = $dataProvider->getTotalCount();

        // page number correction:
        //if ($pager->totalCount <= $pager->pageSize || $page > ceil($pager->totalCount / $pager->pageSize) ) {
        //    $pager->page = 0; //goto 1st page if shortage records
        $maxPage = ceil($pager->totalCount / $pager->pageSize);
        if ($page > $maxPage) {
            $pager->page = $maxPage - 1;
        } else {
            $pager->page = $page - 1; //! from 0
        }//var_dump($page);var_dump($pager->page);

        return $this->render('index', [
            'searchModel'  => $searchModel,
            'dataProvider' => $dataProvider,
            'currentId'    => $id,
        ]);
    }
114368
public function getEditForm($id = null, $fields = null)
    {
        $form = parent::getEditForm($id, $fields);
        $siteConfig = SiteConfig::current_site_config();
        /**
         * SortOrder is ignored unless sortable is enabled.
         */
        if ($this->modelClass === "Tag" && $siteConfig->AllowTags) {
            $form->Fields()
                ->fieldByName('Tag')
                ->getConfig()
                ->addComponent(
                    new GridFieldOrderableRows(
                        'SortOrder'
                    )
                );
        }
        if ($this->modelClass === "News" && !$siteConfig->AllowExport) {
            $form->Fields()
                ->fieldByName("News")
                ->getConfig()
                ->removeComponentsByType('GridFieldExportButton')
                ->addComponent(
                    new GridfieldNewsPublishAction()
                );
        }

        return $form;
    }