savePageAction

@return Response|ResponseInterface

@throws TrackingException
486195
public function savePageAction()
    {
        $request = $this->getRequest();

        //HTTP method check
        if (!$request->isPost()) {
            $response = new Response();
            $response->setStatusCode('405');

            return $response;
        }

        //ACL access check
        if (!$this->rcmUserService->isAllowed(
            $this->getServiceLocator()->get(ResourceName::class)->get(
                ResourceName::RESOURCE_SITES,
                $this->currentSite->getSiteId(),
                ResourceName::RESOURCE_PAGES
            ),
            'edit'
        )
        ) {
            $response = new Response();
            $response->setStatusCode('401');

            return $response;
        }

        // @todo - might validate these against the data coming in
        $pageName = $this->getEvent()
            ->getRouteMatch()
            ->getParam(
                'rcmPageName',
                'index'
            );

        $originalRevisionId = $this->getEvent()
            ->getRouteMatch()
            ->getParam(
                'rcmPageRevision',
                null
            );

        $pageType = $this->getEvent()
            ->getRouteMatch()
            ->getParam(
                'rcmPageType',
                'n'
            );

        //Note: This should probably come out of the ZF2 request instead but that didn't seem to work
        $data = json_decode(file_get_contents('php://input'), true);

        return $this->getJsonResponse(
            $this->pageMutationService->savePageDraft(
                $this->rcmUserService->getCurrentUser(),
                $pageName,
                $pageType,
                $data,
                function ($pageName, $pageType = 'n', $pageRevision = null) {
                    return $this->urlToPage($pageName, $pageType, $pageRevision);
                },
                $originalRevisionId
            )
        );
    }
259247
public function saveAction()
    {
        $services = $this->serviceLocator;

        /* @var \Zend\Http\PhpEnvironment\Request $request */
        $request = $this->getRequest();

        $params          = $this->params();
        $p               = $params->fromPost();
        /* @var \Auth\Entity\User $user */
        $user            = $services->get('AuthenticationService')->getUser();
        $repositories    = $services->get('repositories');
        /* @var \Jobs\Repository\Job $repositoriesJob */
        $repositoriesJob = $repositories->get('Jobs/Job');
        $log             = $services->get('Core/Log');

        $result = array('token' => session_id(), 'isSaved' => false, 'message' => '', 'portals' => array());
        try {
            if (isset($user) && !empty($user->getLogin())) {
                $formElementManager = $services->get('FormElementManager');
                /* @var \Jobs\Form\Import $form */
                $form               = $formElementManager->get('Jobs/Import');
                $id                 = $params->fromPost('id'); // determine Job from Database
                /* @var \Jobs\Entity\Job $entity */
                $entity             = null;
                $createdJob         = true;

                if (empty($id)) {
                    $applyId = $params->fromPost('applyId');
                    if (empty($applyId)) {
                        $entity = $repositoriesJob->create();
                    } else {
                        $entity = $repositoriesJob->findOneBy(array("applyId" => (string) $applyId));
                        if (!isset($entity)) {
                            // new Job (the more likely branch)
                            $entity =$repositoriesJob->create(array("applyId" => (string) $applyId));
                        } else {
                            $createdJob = false;
                        }
                    }
                } else {
                    $repositoriesJob->find($id);
                    $createdJob = false;
                }
                //$services->get('repositories')->get('Jobs/Job')->store($entity);
                $form->bind($entity);
                if ($request->isPost()) {
                    $loginSuffix                   = '';
                    $event                         = $this->getEvent();
                    $event->setName('login.getSuffix');
                    $loginSuffixResponseCollection = $this->getEventManager()->triggerEvent($event);
                    if (!$loginSuffixResponseCollection->isEmpty()) {
                        $loginSuffix = $loginSuffixResponseCollection->last();
                    }
                    $params                        = $request->getPost();
                    $params->datePublishStart      = \Datetime::createFromFormat("Y-m-d", $params->datePublishStart);
                    $result['post']                = $_POST;
                    $form->setData($params);
                    if ($form->isValid()) {
                        if (isset($params['description'])) {
                            $templateValues = new TemplateValues();
                            $description = Json::decode($params->description);
                            $entity->setTemplateValues($templateValues->setDescription(strip_tags($description)));
                        }

                        $entity->setStatus($params['status']);
                        /*
                         * Search responsible user via contactEmail
                         * @var \Auth\Repository\User $users
                         */
                        $users = $repositories->get('Auth/User');
                        $responsibleUser = $users->findByEmail($params['contactEmail']);

                        $entity->setUser($responsibleUser ?: $user);

                        $group = $user->getGroup($entity->getCompany());
                        if ($group) {
                            $entity->getPermissions()->grant($group, PermissionsInterface::PERMISSION_VIEW);
                        }
                        $result['isSaved'] = true;
                        $log->info('Jobs/manage/saveJob [user: ' . $user->getLogin() . ']:' . var_export($p, true));

                        if (!empty($params->companyId)) {
                            $companyId                = $params->companyId . $loginSuffix;
                            $repOrganization          = $repositories->get('Organizations/Organization');
                            $hydratorManager          = $services->get('HydratorManager');
                            /* @var \Organizations\Entity\Hydrator\OrganizationHydrator $hydrator */
                            $hydrator                 = $hydratorManager->get('Hydrator\Organization');
                            $entityOrganizationFromDB = $repOrganization->findbyRef($companyId);
                            //$permissions              = $entityOrganizationFromDB->getPermissions();
                            $data = array(
                                'externalId'      => $companyId,
                                'organizationName' => $params->company,
                                'image'            => $params->logoRef,
                                'user'            => $user
                            );
                            //$permissions->grant($user, PermissionsInterface::PERMISSION_CHANGE);

                            $entityOrganization = $hydrator->hydrate($data, $entityOrganizationFromDB);

                            if ($params->companyUrl) {
                                $entityOrganization->getContact()->setWebsite($params->companyUrl);
                            }

                            if ($responsibleUser && $user !== $responsibleUser) {
                                /*
                                 * We cannot use custom collections yet
                                 * @todo if we updated Mongo ODM to >1.0.5, we must move this to
                                 *       a custom collection class
                                 */
                                $employees = $entityOrganization->getEmployees();
                                $contained = false;
                                /*
                                 * this is o(n) and should propably be optimized when the custom collection is created.
                                 * It's not very performant to load the whole user entity, when all we need is the ID.
                                 * Maybe store the id as reference in the Employees Entity.
                                 */
                                foreach ($employees as $employee) {
                                    if ($employee->getUser()->getId() == $responsibleUser->getId()) {
                                        $contained = true;
                                        break;
                                    }
                                }
                                if (!$contained) {
                                    $employees->add(new Employee($responsibleUser));
                                }
                            }
                            $repositories->store($entityOrganization);
                            $entity->setOrganization($entityOrganization);
                        } else {
                            $result['message'] = '';
                        }

                        if (!empty($params->locations)) {
                            $locations = \Zend\Json\Json::decode($params->locations, \Zend\Json\Json::TYPE_ARRAY);
                            $jobLocations = $entity->getLocations();
                            $jobLocations->clear();
                            foreach ($locations as $locData) {
                                $location = new Location();
                                $coords = array_map(function ($i) {
                                    return (float) $i;
                                }, $locData['coordinates']);
                                $location->setCountry($locData['country'])
                                         ->setRegion($locData['region'])
                                         ->setCity($locData['city'])
                                         ->setCoordinates(new Point($coords));

                                $jobLocations->add($location);
                            }
                        }

                        /* @var \Core\EventManager\EventManager $jobEvents
                         * @var JobEvent $jobEvent */
                        $jobEvents = $services->get('Jobs/Events');
                        $jobEvent = $jobEvents->getEvent(JobEvent::EVENT_IMPORT_DATA, $this);
                        $jobEvent->setJobEntity($entity);

                        $extra = [];
                        foreach (array('channels', 'position', 'branches', 'keywords', 'description') as $paramName) {
                            $data = $params->get($paramName);
                            if ($data) {
                                $data = Json::decode($data, Json::TYPE_ARRAY);
                                $extra[$paramName] = $data;
                                $jobEvent->setParam($paramName, $data);
                            }
                        }

                        $jobEvents->triggerEvent($jobEvent);
                        $repositoriesJob->store($entity);

                        $id = $entity->getId();
                        if (!empty($id)) {
                            $jobEvent = $services->get('Jobs/Event'); // intentinally override
                            $jobEvent->setJobEntity($entity);

                            if (isset($extra['channels'])) {
                                foreach ($extra['channels'] as $portalName => $trash) {
                                    $jobEvent->addPortal($portalName);
                                }
                            }
                            $jobEvent->setParam('extraData', $extra);

                            if ($createdJob || true) {
                                /* @var $jobEvents \Zend\EventManager\EventManager */
                                $jobEvents = $services->get('Jobs/Events');
                                $jobEvent->setName(JobEvent::EVENT_JOB_ACCEPTED);
                                $jobEvent->setTarget($this);
                                $responses = $jobEvents->triggerEvent($jobEvent);

                                foreach ($responses as $response) {
                                    // responses from the portals
                                    // @TODO, put this in some conclusion and meaningful messages
                                    if (!empty($response)) {
                                        if ($response instanceof JobResponse) {
                                            if (!array_key_exists('log', $result)) {
                                                $result['log'] = '';
                                            }
                                            //$message = $response->getMessage();
                                            //$result['log'] .= $response->getMessage() . PHP_EOL;
                                            $status = $response->getStatus();
                                            $portal = $response->getPortal();
                                            if (empty($portal)) {
                                                throw new \RuntimeException('Publisher-Events (internal error): There is an unregistered publisher listening');
                                            }
                                            switch ($status) {
                                                case JobResponse::RESPONSE_FAIL:
                                                case JobResponse::RESPONSE_NOTIMPLEMENTED:
                                                case JobResponse::RESPONSE_ERROR:
                                                    $result['isSaved'] = false;
                                                    break;
                                                case JobResponse::RESPONSE_DENIED:
                                                case JobResponse::RESPONSE_OK:
                                                case JobResponse::RESPONSE_OKANDSTOP:
                                                case JobResponse::RESPONSE_DEPRECATED:
                                                    break;
                                            }
                                            if (array_key_exists($portal, $result['portals'])) {
                                                throw new \RuntimeException('Publisher-Events (internal error): There are two publisher registered for ' . $portal);
                                            }
                                            $result['portals'][$portal] = $status;
                                        } else {
                                            throw new \RuntimeException('Publisher-Events (internal error): Response must be from the class Jobs\Listener\Response\JobResponse');
                                        }
                                    } else {
                                        throw new \RuntimeException('Publisher-Events (internal error): Response must be set');
                                    }
                                }
                            }
                        }
                    } else {
                        $log->info('Jobs/manage/saveJob [error: ' . $form->getMessages() . ']:' . var_export($p, true));
                        $result['valid Error'] = $form->getMessages();
                    }
                }
            } else {
                $log->info('Jobs/manage/saveJob [error: session lost]:' . var_export($p, true));
                $result['message'] = 'session_id is lost';
            }
        } catch (\Exception $e) {
            $result['message'] = 'exception occured: ' . $e->getMessage();
        }
        //$services->get('Core/Log')->info('Jobs/manage/saveJob result:' . PHP_EOL . var_export($p, True));
        return new JsonModel($result);
    }
734444
public function saveSiteAction()
    {
        $request = $this->getRequest();
        $siteId = $request->getPost('site_id', null);
        $status  = 0;
        $errors  = array();
        $textMessage = '';
        $textTitle = '';
        
        $this->getEventManager()->trigger('meliscms_site_save_start', $this, array());
        
        $translator = $this->getServiceLocator()->get('translator');
        $melisTool = $this->getServiceLocator()->get('MelisCoreTool');
        $melisTool->setMelisToolKey(self::TOOL_INDEX, self::TOOL_KEY);
       
        // Getting the Creation/Edition Site Form
        if (is_null($siteId))
        {
            $siteFormType = 'meliscms_site_tool_creation_form';
            $logTypeCode = 'CMS_SITE_ADD';
        }
        else
        {
            $siteFormType = 'meliscms_site_tool_edition_form';
            $logTypeCode = 'CMS_SITE_UPDATE';
        }
        
        $siteForm = $melisTool->getForm($siteFormType);
        
        if($request->isPost()) 
        {
            $siteTable = $this->getServiceLocator()->get('MelisEngineTableSite');
            $domainTable = $this->getServiceLocator()->get('MelisEngineTableSiteDomain');
            $site404Table = $this->getServiceLocator()->get('MelisEngineTableSite404');
            
            $postValues = get_object_vars($request->getPost());
            $postValues = $melisTool->sanitizePost($postValues);
            $siteForm->setData($postValues);
            
            
            
            if($siteForm->isValid()) 
            {
                $data = $siteForm->getData();
                
                $dataSite = array();
                $dataDomain = array();
                $dataSite404 = array();
                $dataSiteLang= null;
                
                if (!empty($data['plang_lang_id'])){
                    $dataSiteLang = $data['plang_lang_id'];
                }
                
                foreach($data as $dataKey => $dataValue) 
                {
                    if(strpos($dataKey, self::SITE_TABLE_PREFIX) !== false) {
                        $dataSite[$dataKey] = $data[$dataKey];
                    }
                    
                    if(strpos($dataKey, self::SITE404_TABLE_PREFIX) !== false) {
                        $dataSite404[$dataKey] = $data[$dataKey];
                    }
                    
                    if(strpos($dataKey, self::DOMAIN_TABLE_PREFIX) !== false) {
                        $dataDomain[$dataKey] = $data[$dataKey];
                    }
                }
                
                $isValidName = false;
                // Checking if the Site name is existing on the site lists
                $siteName = $this->getRequest()->getPost('site_name');
                $siteData = $siteTable->getEntryByField('site_name', $siteName)->current();
                
                if (is_null($siteId))
                {
                    if (empty($siteData))
                    {
                        $isValidName = true;
                    }
                }
                else 
                {
                    if (!empty($siteData))
                    {
                        
                        if ($siteData->site_id == $siteId)
                        {
                            $isValidName = true;
                        }
                    }
                    else 
                    {
                        $isValidName = true;
                    }
                }
                
                if($isValidName) 
                {
                    $genSiteModule = !empty($request->getPost('gen_site_mod')) ? true : false;
                    
                    $cmsSiteSrv = $this->getServiceLocator()->get('MelisCmsSiteService');
                    $saveSiteResult = $cmsSiteSrv->saveSite($dataSite, $dataDomain, $dataSite404, $dataSiteLang, $siteId, $genSiteModule, $dataSite['site_name']);
                    
                    if ($saveSiteResult['success'])
                    {
                        if (is_null($siteId))
                        {
                            $textMessage = 'tr_meliscms_tool_site_add_success';
                        }
                        else 
                        {
                            $textMessage = 'tr_meliscms_tool_site_edit_success';
                        }
                        
                        $siteId = $saveSiteResult['site_id'];
                        // to solve the error on loading css and js
                        // regenerate the melis.modules.path cause the newly created path is not
                        // included in the file
                        $this->regenerateModulesPath();
                        $status = 1;
                    }
                    else 
                    {
                        if ($saveSiteResult['message'] == 'tr_meliscms_tool_site_no_platform_ids')
                        {
                            $textMessage = 'tr_meliscms_tool_site_error_prompt_add';
                            $errors['platformId'] = array(
                                'label' => $translator->translate('tr_meliscms_tool_platform_ids'),
                                'noPlatformIds' => $translator->translate('tr_meliscms_tool_site_no_platform_ids')
                            );
                        }
                        else 
                        {
                            $textMessage = $saveSiteResult['message'];
                        }
                    }
                    
                    unset($data);
                    unset($dataSite);
                    unset($dataSite404);
                    unset($dataDomain);
                }
                else 
                {
                    // if data already exists then add manually the foreign site id key
                    $textMessage = 'tr_meliscms_tool_site_error_prompt_add';
                    $errors = array(
                        'site_name' => array(
                            'siteAlreadyExists' => $translator->translate('tr_meliscms_tool_site_name_exists')
                        ),
                    );
                }
            }
            else 
            {
                if (is_null($siteId))
                {
                    $textMessage = 'tr_meliscms_tool_site_error_prompt_add';
                }
                else
                {
                    $textMessage = 'tr_meliscms_tool_site_edit_failed';
                }
                
                $errors = $siteForm->getMessages();
                $status = 0;
            }
            
            // insert labels and error messages in error array
            $melisMelisCoreConfig = $this->serviceLocator->get('MelisCoreConfig');
            $appConfigForm = $melisMelisCoreConfig->getItem('meliscms/tools/meliscms_tool_site/forms/'.$siteFormType);
            $appConfigForm = $appConfigForm['elements'];
            
            foreach ($errors as $keyError => $valueError)
            {
                foreach ($appConfigForm as $keyForm => $valueForm)
                {
                    if ($valueForm['spec']['name'] == $keyError && !empty($valueForm['spec']['options']['label']))
                    {
                        $errors[$keyError]['label'] = $valueForm['spec']['options']['label'];
                    }
                }
            }
        }
        
        $response = array(
            'success' => $status,
            'textTitle' => 'tr_meliscms_tool_site',
            'textMessage' => $textMessage,
            'errors' => $errors,
            'test' => $errors,
        );

        $this->getEventManager()->trigger('meliscms_site_save_end', $this, array_merge($response, array('typeCode' => $logTypeCode, 'itemId' => $siteId)));
        
        if ($siteId)
        {
            $response['siteId'] = $siteId;
        }
        
        return new JsonModel($response);
    }
626624
function track(backend, eventName, action, label) {

        action = action || location.pathname;
        switch (backend) {

        // ##### Google-Analytics
        case "google-analytics":
            var pageTracker = window._gat && window._gat._getTracker(settings.backends[backend].accountid);
            if (! pageTracker) {
                return;
            }
            if (eventName == PAGEVIEW) {
                pageTracker._trackPageview(action);
            } else {
                // https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
                pageTracker._trackEvent("pilotfish:" + eventName, action, label || "");
            }
            break;

        // ##### Mixpanel
        case "mixpanel":
            if (eventName == PAGEVIEW) {
                window.mixpanel && window.mixpanel.track_pageview(action);
            } else {
                window.mixpanel && window.mixpanel.track(eventName, {action: action, label: label});
            }
            break;

        // ##### Pilotfish Session
        case "pilotfish-session":
            var session = window.sessionStorage;

            if (! session) {
                return;
            }
            if (eventName == PAGEVIEW) {
                // Increment a counter in sessionStorage.
                // Retrieve with `Pilotfish('session', 'pageViews')`
                Pilotfish('session', 'INCR', 'pageViews');
            } else {
                // Store events in a list in sessionStorage as JSON
                // Retrieve with `Pilotfish('session', 'events')`
                Pilotfish('session', 'PUSH', 'events', {eventName: eventName, action: action, label: label});
            }
            break;

        // ##### TODO: Pilotfish API as a backend

        // ##### Quantcast
        case "quantcast":
            if (eventName == PAGEVIEW) {
                window._qevents && window._qevents.push({qacct: settings.backends[backend].accountid});
                // Reload the js. It won't *actually* reload it network-wise, because it will be cached
                Pilotfish('loadScript', (location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js");
            }
            break;


        // ##### Unrecognized
        default:
            Pilotfish('perror', "Invalid backend for recorder");
            break;
        }
    }
1035825
public function save() {
		if($this->persistent) {
			$action = $this->{'update'};
			$action->directCall($this->attrsForApi($action));
			
		} else {
			// insert
			$action = $this->{'create'};
			$ret = new Response($action, $action->directCall($this->attrsForApi($action)));
			
			if($ret->isOk()) {
				$this->attrs = array_merge($this->attrs, (array) $ret->getResponse());
				
			} else {
				throw new Exception\ActionFailed($ret, "Action '".$action->name()."' failed: ".$ret->message());
			}
			
			$this->persistent = true;
		}
	}
857480
protected function setPagerListBackup()
    {
        $options = $this->query_filter;
        $options['count'] = true;

        $pager = array(
            'query' => $this->query_filter,
            'total' => (int) $this->backup->getList($options)
        );

        return $this->data_limit = $this->setPager($pager);
    }
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);
    }
569393
public function sendTracking(Tracking\AbstractTracking $tracking)
    {
        $responseCollection = $this->callEndpoint($tracking);
        $responseCollection->rewind();
        return $responseCollection->current();
    }
352065
private function SaveNew()
    {
        $treeBuilder = new TreeBuilder(new PageTreeProvider($this->site));
        $treeBuilder->Insert($this->page, $this->parent, $this->previous);
    }
1056697
public void savePreviousPageInfo( ActionForward forward, ActionForm form, ActionMapping mapping,
                                      HttpServletRequest request, ServletContext servletContext,
                                      boolean isSpecialForward )
    {
        if ( forward != null )
        {
            //
            // If previous-page is disabled (unused in this pageflow), or if we've already saved prevous-page info in
            // this request (for example, forward to foo.faces which forwards to foo.jsp), just return.
            //
            if ( request.getAttribute( SAVED_PREVIOUS_PAGE_INFO_ATTR ) != null || isPreviousPageInfoDisabled() ) return;

            String path = forward.getPath();
            int queryPos = path.indexOf( '?' );
            if ( queryPos != -1 ) path = path.substring( 0, queryPos );

            //
            // If a form bean was generated in this request, add it to the most recent PreviousPageInfo, so when we
            // go back to that page, the *updated* field values are restored (i.e., we don't revert to the values of
            // the form that was passed into the page originally).
            //
            if ( form != null && _currentPageInfo != null )
            {
                ActionForm oldForm = _currentPageInfo.getForm();
                if ( oldForm == null || oldForm.getClass().equals( form.getClass() ) )
                {
                    _currentPageInfo.setForm( form );
                    _currentPageInfo.setMapping( mapping );
                }
            }

            //
            // Only keep track of *pages* forwarded to -- not actions or pageflows.
            //
            if ( ! FileUtils.osSensitiveEndsWith( path, ACTION_EXTENSION ) )
            {
                //
                // Only save previous-page info if the page is within this pageflow.
                //
                if ( isLocalFile( forward ) ) // || PageFlowUtils.osSensitiveEndsWith( path, JPF_EXTENSION ) )
                {
                    _previousPageInfo = _currentPageInfo;
                    _currentPageInfo = new PreviousPageInfo( forward, form, mapping, request.getQueryString() );
                    request.setAttribute( SAVED_PREVIOUS_PAGE_INFO_ATTR, Boolean.TRUE );
                }
            }
        }
    }
1012780
public function store(PageRequest $request)
    {
        try {
            $data              = $request->all();
            $data['user_id']   = user_id();
            $data['user_type'] = user_type();
            $data              = $this->repository->create($data);
            $message           = trans('messages.success.created', ['Module' => trans('page::page.name')]);
            $code              = 204;
            $status            = 'success';
            $url               = guard_url('page/page/' . $page->getRouteKey());
        } catch (Exception $e) {
            $message = $e->getMessage();
            $code    = 400;
            $status  = 'error';
            $url     = guard_url('page/page');
        }
        return compact('data', 'message', 'code', 'status', 'url');
    }
190391
public function createNewPageFromTemplate($user, $data)
    {
        if (empty($user)) {
            throw new TrackingException('A valid user is required in ' . get_class($this));
        }
        $validatedData = $data;
        /** @var \Rcm\Entity\Page $page */
        $page = $this->pageRepo->findOneBy(
            [
                'pageId' => $validatedData['page-template'],
                'pageType' => 't'
            ]
        );

        if (empty($page)) {
            throw new PageNotFoundException(
                'No template found for page id: '
                . $validatedData['page-template']
            );
        }

        $pageData = [
            'name' => $validatedData['name'],
            'pageTitle' => $validatedData['pageTitle'],
            'pageType' => 'n', // "n" means "normal"
            'createdByUserId' => $user->getId(),
            'createdReason' => 'New page from template in ' . get_class($this),
            'author' => $user->getName(),
        ];

        $createdPage = $resultRevisionId = $this->pageRepo->copyPage(
            $this->currentSite,
            $page,
            $pageData
        );

        $this->immuteblePageVersionRepo->createUnpublished(
            new PageLocator(
                $this->currentSite->getSiteId(),
                $this->rcmPageNameToPathname->__invoke($createdPage->getName(), $createdPage->getPageType())
            ),
            $this->immutablePageContentFactory->__invoke(
                $createdPage->getPageTitle(),
                $createdPage->getDescription(),
                $createdPage->getKeywords(),
                $this->revisionRepo->find($resultRevisionId)->getPluginWrappers()->toArray()
            ),
            $user->getId(),
            __CLASS__ . '::' . __FUNCTION__
        );
    }
623757
public function save(Request $request)
    {
        $this->validate(request(), [//@todo create custom Request class for page validation
            'page_title' => 'max:185',
        ]);
        if($request['create']){
            $this->page->create($request);
        } if($request['update']){
            $this->page->updatePage($request);
        }
        return redirect()->route('dashboard.pages');
    }
889066
public function copyAction()
    {
        $trackId    = $this->_getIdParam();
        $engine     = $this->getTrackEngine();
        $newTrackId = $engine->copyTrack($trackId);

        $this->_reroute(array('action' => 'edit', \MUtil_Model::REQUEST_ID => $newTrackId));
    }
625073
public function indexAction()
    {
        if ($this->getRequest()->isAjax()) {
            try {
                $this->loadLayout(null, false, false);
                $this->getLayout()->getUpdate()->setCacheId(null);
                $this->getLayout()->getUpdate()->addHandle(strtolower($this->getFullActionName()) . '_AJAX');
            } catch (Exception $e) {
                Mage::logException($e);
                $this->getResponse()->setHeader('Content-Type', 'application/json');
                $this->getResponse()->setBody(Zend_Json::encode(['error' => true, 'message' => $e->getMessage()]));
            }
        }

        $this->loadLayout();
        $this->renderLayout();
    }
319589
public function successAction()
    {
        // get the response data
        $response = $this->getRequest()->getParams();

        // process
        try {
            $result = $this->validateResultUrl($response);

            if ($result) {
                $session = $this->_getCheckout();
                $session->unsAdyenRealOrderId();
                $session->setQuoteId($session->getAdyenQuoteId(true));
                $session->getQuote()->setIsActive(false)->save();
                $this->_redirect('checkout/onepage/success', array('utm_nooverride' => '1'));
            } else {
                $this->cancel();
            }
        } catch (Exception $e) {
            Mage::logException($e);
            throw $e;
        }
    }
268101
public function savePropertiesAction()
	{
		$idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', ''));
		$isNew = $this->params()->fromRoute('isNew', $this->params()->fromQuery('isNew', ''));
		$translator = $this->serviceLocator->get('translator');
		
		$eventDatas = array('idPage' => $idPage, 'isNew' => $isNew);
		$this->getEventManager()->trigger('meliscms_page_saveproperties_start', null, $eventDatas);
		
		// Get the form properly loaded
		$propertyForm = $this->getPropertyPageForm($idPage, $isNew);
	
		$melisPageSavedTable = $this->getServiceLocator()->get('MelisEngineTablePageSaved');
    	$melisPagePublishedTable = $this->getServiceLocator()->get('MelisEngineTablePagePublished');
        $melisTool = $this->getServiceLocator()->get('MelisCoreTool');
		// Check if post
		$request = $this->getRequest();
		if ($request->isPost())
		{
		    // Get the current page id from platform table
		    $melisModuleName = getenv('MELIS_PLATFORM');
		    $melisEngineTablePlatformIds = $this->getServiceLocator()->get('MelisEngineTablePlatformIds');
		    $datasPlatformIds = $melisEngineTablePlatformIds->getPlatformIdsByPlatformName($melisModuleName);
		    $datasPlatformIds = $datasPlatformIds->current();
		    
		    if (!empty($datasPlatformIds))
		    {
        		// Get values posted and set them in form
                $postValues = $this->params()->fromRoute();
                if(!isset($postValues['page_duplicate_event_flag'])) {
                    $postValues = get_object_vars($request->getPost());
                    $postValues = $melisTool->sanitizePost($postValues);
                }

        		$propertyForm->setData($postValues);
               
                if (!$isNew)
                {
                    // Set Page lang id not required
                    $propertyForm->getInputFilter()->get('plang_lang_id')->setRequired(false);
                }
        		
        		// Validate the form 
        		if ($propertyForm->isValid())
        		{
        			// Get datas validated
        			$datas = $propertyForm->getData();
        
        			/**
        			 * First, let's copy the published table entry
        			 * inside the saved table if there's no entry in it.
        			 * Kind of special case, the page is not new, it's being edited after being published
        			 */
        			if (!$isNew)
        			{
        				$dataSaved = $melisPageSavedTable->getEntryById($idPage);
        				$dataSaved = $dataSaved->toArray();
        				if (count($dataSaved) == 0)
        				{
        					$dataPublished = $melisPagePublishedTable->getEntryById($idPage);
        					$dataPublished = $dataPublished->toArray();
        					if (count($dataPublished) > 0)
        					{
        						$dataPublished = $dataPublished[0];
        						$melisPageSavedTable->save($dataPublished, $idPage);
        					}
        				}
        			}
        			else
        			{
        				// New page, create an empty content
        				$newXmlContent = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        				$newXmlContent .= '<document type="MelisCMS" author="MelisTechnology" version="2.0">' . "\n";
        				$newXmlContent .= '</document>';
        				$datas['page_content'] = $newXmlContent;
        			}
        			
        			
        			/**
        			 * Datas are all saved in PageSave once validated.
        			 * This allow to add fields in the app.form and fields in the db.
        			 * It will then works with the new field as long as it's in the same table.
        			 * 
        			 * Useless fields from the form must be unset
        			 * Special fields must be set
        			 */
        
        			
        			$errors = array();
        			$success = 0;
        			$language = $datas['plang_lang_id'];
        			$template = $datas['page_tpl_id'];
        			
        			unset($datas['page_submit']);
        			unset($datas['page_creation_date']);
        			unset($datas['plang_lang_id']);
        			unset($datas['style_id']);
        			
        			$datas['page_id'] = $idPage;
        			
        			if(empty($template)) {
        			    $errors = array(
        			        'page_tpl_id' => array(
        			            'errorMessage' => $translator->translate('tr_meliscms_page_form_page_tpl_id_invalid'),
        			            'label' => $translator->translate('tr_meliscms_page_tab_properties_form_Template'),
        			        ),
        			    );
        			}
        			
        			if ($isNew) 
        			{
        			    $datas['page_creation_date'] = date('Y-m-d H:i:s');
        			    
        			    if(empty($language)) {
        			        $errors = array(
        			            'plang_lang_id' => array(
        			                'errorMessage' => $translator->translate('tr_meliscms_page_form_page_p_lang_id_invalid'),
        			                'label' => $translator->translate('tr_meliscms_page_tab_properties_form_Language'),
        			            ),
        			        );
        			    }
        			}
        			else 
        			{
        			    $datas['page_edit_date'] = date('Y-m-d H:i:s');
        			    
        			    $melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth');
        			    $user = $melisCoreAuth->getIdentity();
        			    if (!empty($user))
        			    	$datas['page_last_user_id'] = $user->usr_id;
        			}
        				
        			
        				
        			if(empty($errors))	{
        			    $success = 1;
        			    $res = $melisPageSavedTable->save($datas, $idPage);
        			}
        			    
        
        			$result = array(
        					'success' => $success,
        					'errors' => array($errors),
        			);
        
        		}
        		else
        		{
        			// Get validation errors
        			$result = array(
        					'success' => 0,
        					'errors' => array($propertyForm->getMessages()),
        			);
        		}
		    }
		    else 
		    {
		        $errors = array(
		            'platform_ids' => array(
		                'noPlatformIds' => $translator->translate('tr_meliscms_no_available_platform_ids'),
		                'label' => $translator->translate('tr_meliscms_tool_platform_ids'),
		            ),
		        );
		        
		        $result = array(
		            'success' => 0,
		            'errors' => array($errors),
		        );
            }
		}
		else
		{
			$result = array(
					'success' => 0,
					'errors' => array(array('empty' => $translator->translate('tr_meliscms_form_common_errors_Empty datas'))),
			);
		}

		$this->getEventManager()->trigger('meliscms_page_saveproperties_end', null, $result);
		
		return new JsonModel($result);
	}