savePageDraft

@return Response|ResponseInterface

@throws TrackingException
965297
public function savePageDraft(
        UserInterface $user,
        string $pageName,
        string $pageType,
        $data,
        $urlToPageFunction,
        int $originalRevisionId
    ) {
        if (empty($user)) {
            throw new TrackingException('A valid user is required in ' . get_class($this));
        }

        $this->prepSaveData($data);

        $result = $this->pageRepo->savePage(
            $this->currentSite,
            $pageName,
            $originalRevisionId,
            $pageType,
            $data,
            $user->getId(),
            'Save existing page in ' . get_class($this),
            $user->getName()
        );

        /**
         * If the pageRepo deterimins there was no change, it saves nothing a returns and empty $resultRevisionId.
         */
        $savedANewVersion = !empty($result['newPageRevisionId']);

        if ($savedANewVersion) {
            $resultPageRevisionId = $result['newPageRevisionId'];
            /**
             * @var Page
             */
            $page = $this->pageRepo->findOneBy([
                'site' => $this->currentSite,
                'name' => $pageName,
                'pageType' => $pageType
            ]);

            $this->immuteblePageVersionRepo->createUnpublished(
                new PageLocator(
                    $this->currentSite->getSiteId(),
                    $this->rcmPageNameToPathname->__invoke($pageName, $pageType)
                ),
                $this->immutablePageContentFactory->__invoke(
                    $page->getPageTitle(),
                    $page->getDescription(),
                    $page->getKeywords(),
                    $this->revisionRepo->find($resultPageRevisionId)->getPluginWrappers()->toArray()
                ),
                $user->getId(),
                __CLASS__ . '::' . __FUNCTION__
            );
        }

        /**
         * @var $container Container
         */
        foreach ($result['modifiedSiteWideContainers'] as $revisionId => $container) {
            $this->immutableSiteWideContainerRepo->publish(
                new SiteWideContainerLocator($container->getSiteId(), $container->getName()),
                new ContainerContent(
                    $this->immutablePageContentFactory->pluginWrappersToFlatBlockInstances(
                        $this->revisionRepo->find($revisionId)->getPluginWrappers()->toArray()
                    )
                ),
                $user->getId(),
                __CLASS__ . '::' . __FUNCTION__
            );
        }

        if ($savedANewVersion) {
            $return['redirect'] = $urlToPageFunction(
                $pageName,
                $pageType,
                $resultPageRevisionId
            );
        } else {
            $return['redirect'] = $urlToPageFunction(
                $pageName,
                $pageType,
                $originalRevisionId
            );
        }

        return $return;
    }
525678
public function get_data() {
        $data = parent::get_data();
        if (!empty($data->saveguide)) {
            $data->status = gradingform_controller::DEFINITION_STATUS_READY;
        } else if (!empty($data->saveguidedraft)) {
            $data->status = gradingform_controller::DEFINITION_STATUS_DRAFT;
        }
        return $data;
    }
376898
public function saveAction()
    {
        $success = 0;
        $message = 'tr_melis_cms_prospects_theme_failed';
        $errors  = [];
        $title   = 'tr_melis_cms_prospects_theme';
        $request = $this->getRequest();
        $id      = null;
        if($request->isPost()) {

            $allowSave = false;


            $data = $this->tool()->sanitizeRecursive(get_object_vars($request->getPost()), ["'",'"'], false);
            $id   = isset($data['pros_theme_id']) ? (int) $data['pros_theme_id'] : null; // changed to 1
            
            $melisCoreConfig = $this->serviceLocator->get('MelisCoreConfig');
            $appConfigForm = $melisCoreConfig->getFormMergedAndOrdered('melistoolprospects/tools/melistoolprospects_tool_prospects_themes/forms/prospects_theme_form','prospects_theme_form');
            $factory = new \Zend\Form\Factory();
            $formElements = $this->serviceLocator->get('FormElementManager');
            $factory->setFormElementManager($formElements);
            $form = $factory->createForm($appConfigForm);
            
            $form->setData($data);
            
            if($form->isValid()) {
                $checkData = $this->themeTable()->getEntryByField('pros_theme_name', $data['pros_theme_name'])->current();
                unset($data['pros_theme_id']);

                if(!$checkData && !$id) {
                    $allowSave = true;
                }
                elseif($id && $checkData) {
                    $currentCode = $this->themeTable()->getEntryById($id)->current()->pros_theme_code;
                    if($currentCode != $data['pros_theme_code']) {
                        // recheck if the code exists
                        $checkData = $this->themeTable()->getEntryByField('pros_theme_code', $data['pros_theme_code'])->current();
                        if(empty($checkData)) {
                            $allowSave = true;
                        }
                        else {
                            $message = 'tr_melis_cms_prospects_theme_code_exists';
                        }
                    }
                    else {
                        $allowSave = true;
                    }
                }
                else {
                    $allowSave = true;
                }

                if($allowSave) {
                    $this->themeTable()->save($data, $id);
                    $success = 1;
                    $message = 'tr_melis_cms_prospects_theme_success';
                }
            }
            else {
                $errors = $form->getMessages();
                foreach ($errors as $keyError => $valueError)
                {
                    foreach ($appConfigForm as $keyForm => $valueForm)
                    {
                        if(isset($valueForm['spec']['name']))
                        {
                            if ($valueForm['spec']['name'] == $keyError &&
                                !empty($valueForm['spec']['options']['label'])
                            )
                                $errors[$keyError]['label'] = $valueForm['spec']['options']['label'];
                        }
                    }
                }
            }

        }

        $response = [
            'success'     => $success,
            'errors'      => $errors,
            'textMessage' => $this->tool()->getTranslation($message),
            'textTitle'   => $this->tool()->getTranslation($title)
        ];

        $this->getEventManager()->trigger('meliscmsprospects_theme_save_end', $this, array_merge($response, array('typeCode' => 'CMS_PROSPECTS_THEME_SAVE', 'itemId' => $id)));

        return new JsonModel($response);
    }
298106
public function preparePaginationResponse()
    {
        return new Response($this->total, $this->perPage, $this->page, $this->lastPage);
    }
1213341
public function saveHandler()
    {
        if ($this->changed) {
            $class = $this->getRemoteClass();
            (new $class)->entity->updateRelatedThroughTable($this->table, $this->remoteAttributeName, $this->relatedAttributeName, $this->getIds(), $this->model, $this->filterList);
        }
    }
986934
public function trackPage($page = null, $title = null, $hittype = null)
    {
        $allowedHitTypes = ['pageview', 'appview', 'event', 'transaction', 'item', 'social', 'exception', 'timing'];
        if ($hittype === null) {
            $hittype = $allowedHitTypes[0];
        }

        if (!in_array($hittype, $allowedHitTypes)) {
            return;
        }

        $trackingCode = "ga('send', 'pageview');";

        if ($page !== null || $title !== null || $hittype !== null) {
            $page = ($page === null) ? "window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.search" : "'{$page}'";
            $title = ($title === null) ? "document.title" : "'{$title}'";

            $trackingCode = "ga('send', {'hitType': '{$hittype}', 'page': {$page}, 'title': {$title}});";
        }

        $this->trackingBag->add($trackingCode);
    }
885696
public function cancelDraftAction(Request $request, $id = null)
    {
        /** @var $draftPage PageInterface */
        $draftPage = $this->admin->getObject($id);

        if (!$draftPage) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }

        if (false === $this->admin->isGranted('EDIT', $draftPage)) {
            throw new AccessDeniedException();
        }

        if ($request->getMethod() == 'POST') {
            $pageManager = $this->get('networking_init_cms.page_manager');
            $serializer = $this->get('jms_serializer');

            $publishedPage = $pageManager->revertToPublished($draftPage, $serializer);

            if ($request->isXmlHttpRequest()) {
                $form = $this->admin->getForm();
                $form->setData($publishedPage);

                $pageSettingsTemplate = $this->render(
                    $this->admin->getTemplate('edit'),
                    [
                        'action' => 'edit',
                        'form' => $form->createView(),
                        'object' => $publishedPage,
                    ]
                );

                return $this->renderJson(
                    [
                        'result' => 'ok',
                        'objectId' => $this->admin->getNormalizedIdentifier($publishedPage),
                        'title' => $publishedPage->__toString(),
                        'pageStatus' => $this->translate($publishedPage->getStatus()),
                        'pageSettings' => $pageSettingsTemplate->getContent(),
                    ]
                );
            }

            return $this->redirect($this->admin->generateObjectUrl('edit', $publishedPage));
        }

        return $this->renderWithExtraParams(
            '@NetworkingInitCms/PageAdmin/page_cancel_draft.html.twig',
            [
                'action' => 'cancelDraft',
                'page' => $draftPage,
                'admin' => $this->admin,
            ]
        );
    }
1182167
public function save()
    {
        $resourceResponse = null;

        if ($this->isCreatable() && !$this->isUpdateable()) { //available for creation
            $resourceResponse = $this->planResource->save($this->transform(ModelInterface::TRANSFORM_TO_JSON_ARRAY));
        }

        if ($this->isUpdateable() && !$this->isCreatable()) { //available for update
            $resourceResponse = $this->planResource->update(
                $this->plan_code,
                $this->transform(ModelInterface::TRANSFORM_TO_JSON_ARRAY)
            );
        }

        if ($resourceResponse == null) {
            throw new \InvalidArgumentException('You Cant Perform This Operation on an empty plan');
        }

        if ($resourceResponse instanceof \Exception) {
            throw $resourceResponse;
        }

        return $this->_setAttributes($resourceResponse);
    }
392720
public function saveSettingsAction()
    {
        if ($this->ldap->saveSettings($this->request->request->all())) {
            return new Response('true');
        }

        return new Response('false');
    }
717651
protected function _post()
    {
        $subject = $this->_subject([
            'entity' => $this->_entity($this->_request()->data, $this->saveOptions()),
            'saveMethod' => $this->saveMethod(),
            'saveOptions' => $this->saveOptions()
        ]);

        $this->_trigger('beforeRegister', $subject);

        $saveCallback = [$this->_table(), $subject->saveMethod];
        if ($saveCallback($subject->entity, $subject->saveOptions)) {
            return $this->_success($subject);
        }

        return $this->_error($subject);
    }
680260
public function getPage()
    {
        if (null === $this->site || null === $this->layout || null === $this->title) {
            $this->reset();
            throw new \Exception("Required data missing");
        }

        $page = new Page($this->uid);
        $page->setTitle($this->title);
        $page->setSite($this->site);

        if (null !== $this->parent) {
            $page->setParent($this->insureParentIsSection($this->parent));
        }

        $page->setLayout($this->layout, $this->itemToPushInMainZone);

        if (null !== $this->url) {
            $page->setUrl($this->url);
        }

        if (null !== $this->redirect) {
            $page->setRedirect($this->redirect);
        }

        if (null !== $this->target) {
            $page->setTarget($this->target);
        }

        if (null !== $this->altTitle) {
            $page->setAltTitle($this->altTitle);
        }

        if (null !== $this->state) {
            $page->setState($this->state);
        }

        if (null !== $this->publishedAt) {
            $page->setPublishing($this->publishedAt);
        }

        if (null !== $this->createdAt) {
            $page->setCreated($this->createdAt);
        }

        if (null !== $this->archiving) {
            $page->setArchiving($this->archiving);
        }

        $pageContentSet = $page->getContentSet();
        $this->updateContentRevision($pageContentSet);
        while ($column = $pageContentSet->next()) {
            $this->updateContentRevision($column);
        }

        if (0 < count($this->elements)) {
            foreach ($this->elements as $e) {
                $column = $pageContentSet->item($e['content_set_position']);
                if ($e['set_main_node']) {
                    $e['content']->setMainNode($page);
                }

                $column->push($e['content']);
            }

            $pageContentSet->rewind();
        }

        $this->doPersistIfValid($page);

        $this->reset();

        return $page;
    }
370428
public function post()
    {
        $request = $this->getDI()->get('request');
        // supply everything the request object could possibly need to fulfill the request
        $post = $request->getJson($this->getControllerName('singular'), $this->getModel());

        if (!$post) {
            throw new HTTPException('There was an error adding new record.  Missing POST data.', 400, [
                'dev' => 'Invalid data posted to the server',
                'code' => '568136818916816555'
            ]);
        }

        if(method_exists($this->model, "getBlockColumns")) {
            // filter out any block columns from the posted data
            $blockFields = $this->model->getBlockColumns();
            foreach ($blockFields as $key => $value) {
                unset($post->$value);
            }
        }

        $post = $this->beforeSave($post);
        // This record only must be created
        $id = $this->entity->save($post);
        $this->afterSave($post, $id);

        // now fetch the record so we can return it
        $result = $this->entity->findFirst($id);

        if ($result->countResults() == 0) {
            // This is bad. Throw a 500. Responses should always be objects.
            throw new HTTPException('There was an error retrieving the newly created record.', 500, [
                'dev' => 'The resource you requested is not available after it was just created',
                'code' => '1238510381861'
            ]);
        } else {
            return $result;
        }
    }
835155
public function save() {
        global $DB;
        if (empty($this->id)) {
            $r = (object)array(
                'data' => base64_encode(serialize($this)),
                'expirytime' => time() + (60*60*24),
                'userid' => $this->user->id,
                'instance' => (empty($this->instance)) ? null : $this->instance->get('id'),
            );
            $this->id = $DB->insert_record('portfolio_tempdata', $r);
            $this->expirytime = $r->expirytime;
            $this->save(); // call again so that id gets added to the save data.
        } else {
            if (!$r = $DB->get_record('portfolio_tempdata', array('id' => $this->id))) {
                if (!$this->deleted) {
                    //debugging("tried to save current object, but failed - see MDL-20872");
                }
                return;
            }
            $r->data = base64_encode(serialize($this));
            $r->instance = (empty($this->instance)) ? null : $this->instance->get('id');
            $DB->update_record('portfolio_tempdata', $r);
        }
    }
866221
public function buildDraftValue() {
		$this->targetDraftFetcher->getFetchDraftStmtBuilder()->bindValue(
				$this->phName, $this->fetchDraftStmtBuilder->getBoundIdRawValue());
		
		return $this->targetDraftFetcher->fetch();
	}
944549
public function save()
    {
        if (!$this->path)
        {
            return;
        }
        while (count($this->actionQueue))
        {
            $action = array_shift($this->actionQueue);
            $methodName = 'action' . $action['action'];
            if (!method_exists($this, $methodName))
            {
                throw new LogicException('Unknown action: ' . $action['action']);
            }
            call_user_func_array(array($this, $methodName), $action['args']);
        }
        if ($this->phpThumb)
        {
            $this->phpThumb->save($this->path);
        }
    }
272800
public static function trackChanges()
    {
        self::_initialize(true);

        while (self::$_tracking) {
            $newGoalState = self::$_runtimeClient->getCurrentGoalState();

            switch ($newGoalState->getExpectedState()) {
            case CurrentStatus::STARTED:
                $newIncarnation = $newGoalState->getIncarnation();
                $currentIncarnation = self::$_currentGoalState->getIncarnation();

                if ($newIncarnation > $currentIncarnation) {
                    self::_processGoalStateChange($newGoalState);
                }

                break;
            case CurrentStatus::STOPPED:
                self::_raiseStoppingEvent();

                $stoppedState = new AcquireCurrentState(
                    self::$_clientId,
                    $newGoalState->getIncarnation(),
                    CurrentStatus::STOPPED,
                    self::$_maxDateTime
                );

                self::$_runtimeClient->setCurrentState($stoppedState);
                break;
            }

            if (is_int(self::$_tracking)) {
                --self::$_tracking;
            }
        }
    }
1075491
protected function SaveElement()
    {
        $this->articleList->SetArticlePage($this->articlePageSelector->GetPage());
        $archiveCat = explode('-', $this->Value('ArchiveCategory'));
        $this->CleanPageArticleLists();
        if (count($archiveCat) == 1) {
            $this->SaveArchivePage($archiveCat[0]);
        }
        else if (count($archiveCat) == 2) {
            $this->SaveCategoryPage($archiveCat[1]);
        }
        return $this->articleList;
    }