Save an Element Type data tree.

@param Request $request

@return ResultResponse
@Route("/save", name="elementtypes_tree_save")
353049
public function saveAction(Request $request)
    {
        $treeSaver = $this->get('phlexible_elementtype.tree_saver');

        $elementtype = $treeSaver->save($request, $this->getUser());

        return new ResultResponse(
            true,
            "Element Type {$elementtype->getTitle()} saved as version {$elementtype->getRevision()}."
        );
    }
610844
public function save(Request $request, UserInterface $user)
    {
        $eid = $request->get('eid');
        $language = $request->get('language');
        $tid = $request->get('tid');
        $teaserId = $request->get('teaser_id');
        $isPublish = $request->get('isPublish');
        $values = $request->get('values');
        $publishComment = $request->get('publishComment');

        if ($values) {
            $values = json_decode($values, true);
        }

        $element = $this->elementService->findElement($eid);
        $elementtype = $this->elementService->findElementtype($element);
        $elementtypeStructure = $elementtype->getStructure();

        $oldElementVersion = $this->elementService->findLatestElementVersion($element);
        $oldElementStructure = $this->elementService->findElementStructure($oldElementVersion, 'de');
        $oldVersion = $oldElementVersion->getVersion();
        $isMaster = $element->getMasterLanguage() === $language;

        $tree = $this->treeManager->getByNodeId($tid);
        $node = $tree->get($tid);

        $teaser = null;
        if ($teaserId) {
            $teaser = $this->teaserManager->find($teaserId);
        }

        $comment = null;
        if ($request->get('comment')) {
            $comment = $request->get('comment');
        }

        if ($language === $element->getMasterLanguage()) {
            $elementStructure = new ElementStructure();
            if ($oldElementStructure->getDataId()) {
                $elementStructure
                    ->setDataId($oldElementStructure->getDataId())
                    ->setDsId($oldElementStructure->getDsId())
                    ->setType('root')
                    ->setName($oldElementStructure->getName());
            } else {
                $elementStructure
                    ->setDataId(UuidUtil::generate())
                    ->setDsId($elementtypeStructure->getRootDsId())
                    ->setType('root')
                    ->setName($elementtypeStructure->getRootNode()->getName());
            }
            $map = $this->applyStructure($elementStructure, $elementtypeStructure, $values, $language, $oldElementStructure);
            $this->applyOldValues($elementStructure, $oldElementStructure, $elementtypeStructure, $language);
            $this->applyValues($elementStructure, $elementtypeStructure, $values, $language, $map, null);
        } else {
            $elementStructure = clone $oldElementStructure;
            $this->applyValues($elementStructure, $elementtypeStructure, $values, $language, null, $element->getMasterLanguage());
        }

        $elementStructure->setId(null);

        $rii = new \RecursiveIteratorIterator($elementStructure->getIterator(), \RecursiveIteratorIterator::SELF_FIRST);
        foreach ($rii as $structure) {
            /* @var $structure ElementStructure */
            $structure->setId(null);
        }

        $elementVersion = $this->elementService->createElementVersion($element, $elementStructure, $language, $user->getId(), $comment);

        if ($teaser) {
            $this->saveTeaserData($teaser, $language, $request);
        } else {
            $this->saveNodeData($node, $language, $request);
        }

        // TODO: available languages
        $this->saveMeta($elementVersion, $language, $isMaster, ['de'], $request);

        $event = new SaveElementEvent($element, $language, $oldVersion);
        $this->eventDispatcher->dispatch(ElementEvents::SAVE_ELEMENT, $event);

        $publishSlaves = [];
        if ($isPublish) {
            $publishSlaves = $this->checkPublishSlaves($elementVersion, $node, $teaser, $language);
            if ($teaser) {
                $this->publishTeaser($elementVersion, $teaser, $language, $user->getId(), $publishComment, $publishSlaves);
            } else {
                $this->publishTreeNode($elementVersion, $node, $language, $user->getId(), $publishComment, $publishSlaves);
            }
        }

        $status = '';
        if ($teaser) {
            if ($this->teaserManager->isPublished($teaser, $language)) {
                $status = $this->teaserManager->isAsync($teaser, $language) ? 'async' : 'online';
            }
        } else {
            if ($tree->isPublished($node, $language)) {
                $status = $tree->isAsync($node, $language) ? 'async' : 'online';
            }
        }

        return [$elementVersion, $node, $teaser, $publishSlaves, $status];
    }
1172131
public function save(Request $request, UserInterface $user)
    {
        $elementtypeId = $request->get('element_type_id', false);
        $data = json_decode($request->get('data'), true);

        if (!$elementtypeId) {
            throw new InvalidArgumentException('No elementtype ID.');
        }

        $rootData = $data[0];
        $rootType = $rootData['type'];
        $rootProperties = $rootData['properties'];
        $rootConfig = $rootProperties['root'];
        $rootMappings = !empty($rootProperties['mappings']) ? $rootProperties['mappings'] : null;
        $rootDsId = !empty($rootData['ds_id']) ? $rootData['ds_id'] : UuidUtil::generate();

        if (!isset($rootData['type']) || ($rootData['type'] !== 'root' && $rootData['type'] !== 'referenceroot')) {
            throw new InvalidArgumentException('Invalid root node.');
        }

        if (!isset($rootConfig['unique_id']) || !trim($rootConfig['unique_id'])) {
            throw new InvalidArgumentException('No unique ID.');
        }

        $uniqueId = trim($rootConfig['unique_id']);
        $title = trim($rootConfig['title']);
        $icon = trim($rootConfig['icon']);
        $hideChildren = !empty($rootConfig['hide_children']);
        $defaultTab = strlen($rootConfig['default_tab']) ? $rootConfig['default_tab'] : null;
        $defaultContentTab = strlen($rootConfig['default_content_tab']) ? $rootConfig['default_content_tab'] : null;
        $metasetId = strlen($rootConfig['metaset']) ? $rootConfig['metaset'] : null;
        $template = trim($rootConfig['template']) ?: null;
        $comment = trim($rootConfig['comment']) ?: null;

        $elementtype = $this->elementtypeService->findElementtype($elementtypeId);
        $elementtype
            ->setRevision($elementtype->getRevision() + 1)
            ->setUniqueId($uniqueId)
            ->setTitle('de', $title)
            ->setTitle('en', $title)
            ->setIcon($icon)
            ->setHideChildren($hideChildren)
            ->setDefaultTab($defaultTab)
            ->setDefaultContentTab($defaultContentTab)
            ->setMetaSetId($metasetId)
            ->setTemplate($template)
            ->setMappings($rootMappings)
            ->setComment($comment)
            ->setModifyUser($user->getUsername())
            ->setModifiedAt(new \DateTime());

        $elementtypeStructure = null;
        if (isset($rootData['children'])) {
            $fieldData = $rootData['children'];
            $elementtypeStructure = $this->buildElementtypeStructure($rootType, $rootDsId, $user, $fieldData);
            $elementtype->setStructure($elementtypeStructure);
        }

        $this->elementtypeService->updateElementtype($elementtype, false);

        // update elementtypes that use this elementtype as reference

        /*
        if ($elementtype->getType() === 'reference') {
            $this->updateElementtypesUsingReference($elementtype, $user->getId());
        }
        */

        return $elementtype;
    }
931182
public function createAction(Request $request)
    {
        $contentTypeManager = $this->get('opifer.content.content_type_manager');

        $contentType = $contentTypeManager->create();

        $form = $this->createForm(ContentTypeType::class, $contentType);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            foreach ($form->getData()->getSchema()->getAttributes() as $attribute) {
                $attribute->setSchema($contentType->getSchema());

                foreach ($attribute->getOptions() as $option) {
                    $option->setAttribute($attribute);
                }
            }

            $contentTypeManager->save($contentType);

            $this->addFlash('success', 'Content type has been created successfully');

            return $this->redirectToRoute('opifer_content_contenttype_edit', ['id' => $contentType->getId()]);
        }

        return $this->render($this->getParameter('opifer_content.content_type_create_view'), [
            'content_type' => $contentType,
            'form' => $form->createView(),
        ]);
    }
1327469
public function postAction(Request $request)
    {
        try {
            $data = $request->request->all();
            $data['type'] = OrderType::MANUAL;

            $order = $this->getManager()->save(
                $data,
                $this->getLocaleManager()->retrieveLocale($this->getUser(), $request->get('locale')),
                $this->getUser()->getId()
            );

            $view = $this->view($order, 200);
        } catch (OrderDependencyNotFoundException $exc) {
            $exception = new EntityNotFoundException($exc->getEntityName(), $exc->getId());
            $view = $this->view($exception->toArray(), 400);
        } catch (MissingOrderAttributeException $exc) {
            $exception = new MissingArgumentException($this->getOrderEntityName(), $exc->getAttribute());
            $view = $this->view($exception->toArray(), 400);
        }

        return $this->handleView($view);
    }
608089
public function fortypeAction(Request $request)
    {
        $elementtypeService = $this->get('phlexible_elementtype.elementtype_service');

        $for = $request->get('type', Elementtype::TYPE_FULL);

        $elementtypes = $elementtypeService->findAllElementtypes();

        $allowedForFull = $allowedForStructure = $allowedForArea = [
            Elementtype::TYPE_FULL,
            Elementtype::TYPE_STRUCTURE,
        ];
        $allowedForContainer = $allowedForPart = [
            Elementtype::TYPE_LAYOUTAREA,
            Elementtype::TYPE_LAYOUTCONTAINER,
        ];

        $list = [];
        foreach ($elementtypes as $elementtype) {
            $type = $elementtype->getType();

            if ($for === Elementtype::TYPE_FULL && !in_array($type, $allowedForFull)) {
                continue;
            } elseif ($for === Elementtype::TYPE_STRUCTURE && !in_array($type, $allowedForStructure)) {
                continue;
            } elseif ($for === Elementtype::TYPE_REFERENCE) {
                continue;
            } elseif ($for === Elementtype::TYPE_LAYOUTAREA && !in_array($type, $allowedForArea)) {
                continue;
            } elseif ($for === Elementtype::TYPE_LAYOUTCONTAINER && !in_array($type, $allowedForContainer)) {
                continue;
            } elseif ($for === Elementtype::TYPE_PART && !in_array($type, $allowedForPart)) {
                continue;
            }

            $list[] = [
                'id' => $elementtype->getId(),
                'type' => $elementtype->getType(),
                'title' => $elementtype->getTitle(),
                'icon' => $elementtype->getIcon(),
                'version' => $elementtype->getRevision(),
            ];
        }

        return new JsonResponse(['elementtypes' => $list, 'total' => count($list)]);
    }
12377
public function savesetsAction(Request $request)
    {
        $fileId = $request->get('file_id');
        $joinedIds = $request->get('ids');
        if ($joinedIds) {
            $ids = explode(',', $joinedIds);
        } else {
            $ids = [];
        }

        $volumeManager = $this->get('phlexible_media_manager.volume_manager');

        $volume = $volumeManager->getByFileId($fileId);
        $file = $volume->findFile($fileId);
        $volume->setFileMetasets($file, $ids, $this->getUser()->getId());

        return new ResultResponse(true, 'Set added.');
    }
829281
public function treeAction(Request $request)
    {
        $root = $request->attributes->get('root');

        return $this->render($this->template, [
            'root_node' => $root,
            'routing_defaults' => $this->treeConfiguration['routing_defaults'],
            'repository_name' => $this->treeConfiguration['repository_name'],
            'reorder' => $this->treeConfiguration['reorder'],
            'move' => $this->treeConfiguration['move'],
            'sortable_by' => $this->treeConfiguration['sortable_by'],
        ]);
    }
721604
public function saveAction(Request $request)
    {
        $all = $request->get('all');
        $action = $request->get('action');
        $tempId = $request->get('temp_id');

        $metaData = $request->get('meta', null);
        if ($metaData) {
            $metaData = json_decode($metaData, true);
        }

        $tempHandler = $this->get('phlexible_media_manager.upload.temp_handler');

        if ($all) {
            $tempHandler->handleAll($action);
        } else {
            $file = $tempHandler->handle($action, $tempId);

            if ($file && $metaData) {
                $this->saveMeta($file, $metaData);
            }
        }

        return new ResultResponse(true, ($all ? 'All' : 'File').' saved with action '.$action);
    }
263738
public function acceptXml(Request $request)
    {
        $ret = new \DOMDocument("1.0", "UTF-8");
        $ret->preserveWhiteSpace = false;

        $root = $ret->appendChild($ret->createElement("result"));
        $root->appendChild($ret->createCDATASection(var_export([
            "bid"   => $request->get('bid'),
            "id"    => $request->get('id'),
            "piv"   => $request->get('piv'),
        ], true)));

        $refresh_list = $root->appendChild($ret->createElement("refresh_list"));

        if (null === $bid = $request->get("bid")) {
            return new Response('Missing bid parameter', 400);
        }

        try {
            /** @var \databox $databox */
            $databox = $this->findDataboxById((int) $bid);
            $databox->get_connection()->connect();

            $dom = $databox->get_dom_cterms();
            $xpath = new \DOMXPath($dom);
            $q = "/cterms//te[@id='" . $request->get('id') . "']";

            /** @var \DOMElement $te */
            $te = $xpath->query($q)->item(0);
            if ($te) {
                $this->acceptBranch($bid, $te);

                $databox->saveCterms($dom);

                /** @var \DOMElement $r */
                $r = $refresh_list->appendChild($ret->createElement("refresh"));
                /** @var \DOMElement $p */
                $p = $te->parentNode;
                $r->setAttribute("id", $p->getAttribute("id"));
                $r->setAttribute("type", "CT");
            }
        } catch (\Exception $e) {

        }

        return new Response($ret->saveXML(), 200, ['Content-Type' => 'text/xml']);
    }
901862
public function store(Request $request)
    {
        try {
            $blockType = $this->blockTypes->save($request);
        } catch (Exception $e) {
            return $this->handleException($e, trans('soda::errors.create', ['object' => trans('soda::terminology.block_type')]));
        }

        return redirect()->route('soda.block-types.edit', $blockType->getKey())->with('success', trans('soda::messages.created', ['object' => trans('soda::terminology.block_type')]));
    }
167959
public function store(Request $request)
    {
        $createResource = $this->createResourceCallable();
        $resource = new CreateResource($this->serializer);

        $model = $this->getDataModel();
        $data = (array) $request->get('data');
        if (array_key_exists('attributes', $data) && $model->timestamps) {
            $data['attributes'][$model::CREATED_AT] = Carbon::now()->toDateTimeString();
            $data['attributes'][$model::UPDATED_AT] = Carbon::now()->toDateTimeString();
        }

        return $this->addHeaders(
          $resource->get($data, get_class($this->getDataModel()), $createResource)
        );
    }
975646
public function store(Request $request)
    {
        // Validate the form data
        $result = $this->validate($request, [
            'name' => 'required',
            'slug' => 'required|alpha_dash|unique:roles',
        ]);

        // Create the Role
        $role = Sentinel::getRoleRepository()->createModel()->create([
            'name' => trim($request->get('name')),
            'slug' => trim($request->get('slug')),
        ]);

        // Cast permissions values to boolean
        $permissions = [];
        foreach ($request->get('permissions', []) as $permission => $value) {
            $permissions[$permission] = (bool)$value;
        }

        // Set the role permissions
        $role->permissions = $permissions;
        $role->save();

        // All done
        if ($request->expectsJson()) {
            return response()->json(['role' => $role], 200);
        }

        session()->flash('success', "Role '{$role->name}' has been created.");
        return redirect()->route('roles.index');
    }
138566
public function updateTreeAction(Request $request)
    {
        /** @var Request $request */
        $nodes = $request->get('nodes') ? $request->get('nodes') : [];

        $admin = $this->get('networking_init_cms.admin.tag');

        $validator = $this->get('validator');
        try {
            foreach ($nodes as $node) {
                if (!$node['id']) {
                    continue;
                }
                /** @var $tag Tag */
                $tag = $admin->getObject($node['id']);
                if ($node['parent_id']) {
                    $parent = $admin->getObject($node['parent_id']);
                    $tag->setParent($parent);
                } else {
                    $tag->setParent(null);
                }

                $tag->setLevel($node['depth'] + 1);

                $errors = $validator->validate($tag);
                if (count($errors) > 0) {
                    throw new ValidatorException();
                }

                $this->admin->update($tag);
            }

            $response = ['status' => 'success', 'message' => $this->admin->trans('info.tag_sorted')];
        } catch (\Exception $e) {
            $response = ['status' => 'error', 'message' => $this->admin->trans('info.tag_sorted_error')];
        }

        return $this->renderJson($response);
    }
228384
public function saveAction(Request $request)
    {
        $siterootId = $request->get('id');
        $data = json_decode($request->get('data'), true);

        $siteroot = $this->siterootManager->find($siterootId);

        $this
            ->applyTitles($siteroot, $data)
            ->applyProperties($siteroot, $data)
            ->applyNamedTids($siteroot, $data)
            ->applyNavigations($siteroot, $data)
            ->applyUrls($siteroot, $data);

        $this->siterootManager->updateSiteroot($siteroot);

        return $siteroot;
    }
543508
public function savedetailsAction(Request $request)
    {
        $user = $this->getUser()
            ->setFirstname($request->request->get('firstname'))
            ->setLastname($request->request->get('lastname'))
            ->setEmail($request->request->get('email'));

        $this->get('phlexible_user.user_manager')->updateUser($user);

        return new ResultResponse(true, 'User details saved.');
    }
1298744
public function saveAction(Request $request)
	{
		$file = $this->getEntity();

		// set private
		if ($request->request->has('private')) {
			$private = $request->request->get('private');

			if ($private == 0) {
				$this->getFileStorage()->setPublic($file);
			}

			if ($private == 1) {
				$this->getFileStorage()->setPrivate($file);
			}

			$this->container->getDoctrine()->getManager()->flush();

			return new SupraJsonResponse();
		}

		// renaming
		if ($request->request->has('filename')) {

			$fileName = $request->request->get('filename');

			if (trim($fileName) == '') {
				throw new CmsException(null, 'Empty filename not allowed');
			}

			$newFileInfo = pathinfo($fileName);

			if (mb_strlen($newFileInfo['basename'], 'utf-8') > self::MAX_FILE_BASENAME_LENGTH) {

				if ($file instanceof Folder) {
					throw new CmsException(null, 'Folder name is too long! Maximum length is ' . self::MAX_FILE_BASENAME_LENGTH . ' characters!');
				} else {
					throw new CmsException(null, 'File name is too long! Maximum length is ' . self::MAX_FILE_BASENAME_LENGTH . ' characters!');
				}
			}

			try {
				if ($file instanceof Folder) {
					$this->getFileStorage()->renameFolder($file, $fileName);
				} else {
					$this->getFileStorage()->renameFile($file, $fileName);
				}
			} catch (\Exception $e) {
				$key = $e instanceof UploadFilterException ? $e->getMessageKey() : null;
				throw new CmsException($key, $e->getMessage(), $e);
			}
		}

//		// Custom Properties
//		$dirty = false;
//
//		$propertyConfigurations = $this->getFileStorage()->getCustomPropertyConfigurations();
//		foreach ($propertyConfigurations as $configuration) {
//			$propertyName = $configuration->name;
//
//			if ($request->request->has($propertyName)) {
//				$value = $request->request->get($propertyName);
//
//				$property = $this->getFileStorage()->getFileCustomProperty($file, $propertyName);
//
//				$property->setEditableValue($value, $configuration->getEditable());
//
//				$dirty = true;
//			}
//		}
//
//		if ($dirty) {
//			$this->container->getDoctrine()->getManager()->flush();
//		}

		$response = array();

		// when changing image private attribute, previews and thumbs will change their paths
		// so we will output new image info
		if ($file instanceof File) {
			$response = $this->imageAndFileOutput($file);
		}

		return new SupraJsonResponse($response);
	}