Save information about field or create new field
@param int  $structure_id Current structure identifier
@param null $field_id Current field identifier

@return array Ajax response
170053
public function __async_save($structure_id = null, $field_id = null, $edit = null)
    {
        /** @var \samson\cms\web\field\CMSField $currentField */
        $currentField = null;
        $inputName = $_POST['Name'];

        // Check input Name for illegal characters and spaces
        $returnFilter = filter_var($inputName, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/[\\\~^°!\"§$%\/()=?`'; ,\.:_{\[\]}\|<>@+#]/")));
        if ($returnFilter || $inputName == '') {
            return array('status' => 1, 'message' => t('Вы ввели некорректное значение', true));
        }

        if ($this->query->entity('\samson\cms\web\field\CMSField')->where('Name', $inputName)->where('FieldID', $field_id, ArgumentInterface::NOT_EQUAL)->first()) {
            // Field already exists. Cant use this name
            return array('status' => 1, 'message' => t('Поле с таким именем уже существует', true));
        }

        // If this is new field action
        if (!$this->query->entity('\samson\cms\web\field\CMSField')->where('FieldID', $field_id)->first($currentField)) {
            $currentField = new CMSField(false);
        }

        // Update current field
        $currentField->update($structure_id);

        // Show field in list and form or not
        $currentField->showInList = isset($_POST['show-in-list'])&&($_POST['show-in-list'] == true || $_POST['show-in-list'] == 'on') ? 1 : 0;
        $currentField->showInForm = isset($_POST['show-in-form'])&&($_POST['show-in-form'] == true || $_POST['show-in-form'] == 'on') ? 1 : 0;
        $currentField->customTypeName = isset($_POST['customTypeName'])&&($_POST['customTypeName'] != null) ? filter_var($_POST['customTypeName']) : null;
        $currentField->save();

        // Return positive Ajax status
        return $this->__async_renderfields($structure_id);
    }
102922
private function appendNode(ElementtypeStructure $structure, ElementtypeStructureNode $node, Element $element)
    {
        $nodeAttributes = [
            'type' => $node->getType(),
            'dsId' => $node->getDsId(),
            'name' => $node->getName(),
        ];
        if ($node->getReferenceElementtypeId()) {
            $nodeAttributes['referenceElementtypeId'] = $node->getReferenceElementtypeId();
        }

        $nodeElement = $element->appendElement('node', '', $nodeAttributes);

        $labels = $node->getLabels();
        if ($labels) {
            foreach ($labels as $key => $value) {
                foreach ($value as $language => $languageValue) {
                    if (!$languageValue) {
                        unset($labels[$key][$language]);
                    }
                }
            }
            if ($labels) {
                $labelsElement = $nodeElement->appendElement('labels');
                foreach ($labels as $key => $value) {
                    foreach ($value as $language => $languageValue) {
                        $labelsElement->appendElement(
                            'label',
                            $languageValue,
                            [
                                'type' => $key,
                                'language' => $language,
                            ]
                        );
                    }
                }
            }
        }

        $configuration = $node->getConfiguration();
        if ($configuration) {
            foreach ($configuration as $key => $value) {
                if (!$value) {
                    unset($configuration[$key]);
                }
            }
            if ($configuration) {
                $configurationElement = $nodeElement->appendElement('configuration');
                foreach ($configuration as $key => $value) {
                    $attributes = [
                        'key' => $key,
                        'type' => gettype($value),
                    ];
                    if (is_array($value)) {
                        $value = json_encode($value);
                        $attributes['type'] = 'json_array';
                    } elseif (!is_scalar($value)) {
                        throw new InvalidArgumentException('Value has to be array or scalar.');
                    }
                    $configurationElement->appendElement(
                        'item',
                        $value,
                        $attributes
                    );
                }
            }
        }

        $validation = $node->getValidation();
        if ($validation) {
            foreach ($validation as $key => $value) {
                if (!$value) {
                    unset($validation[$key]);
                }
            }
            if ($validation) {
                $validationElement = $nodeElement->appendElement('validation');
                foreach ($validation as $key => $value) {
                    $validationElement->appendElement(
                        'constraint',
                        $value,
                        [
                            'key' => $key,
                        ]
                    );
                }
            }
        }

        $childNodes = $structure->getChildNodes($node->getDsId());
        if ($childNodes) {
            $childrenElement = $nodeElement->appendElement('children');
            foreach ($childNodes as $childNode) {
                $this->appendNode($structure, $childNode, $childrenElement);
            }
        }

        return $nodeElement;
    }
759724
public function seeJsonStructure(array $structure = null, $responseData = null)
    {
        if (is_null($structure)) {
            return $this->seeJson();
        }

        if (is_null($responseData)) {
            $responseData = $this->decodeResponseJson();
        }

        foreach ($structure as $key => $value) {
            if (is_array($value) && $key === '*') {
                $this->assertIsArray($responseData);

                foreach ($responseData as $responseDataItem) {
                    $this->seeJsonStructure($structure['*'], $responseDataItem);
                }
            } elseif (is_array($value)) {
                $this->assertArrayHasKey($key, $responseData);
                $this->seeJsonStructure($structure[$key], $responseData[$key]);
            } else {
                $this->assertArrayHasKey($value, $responseData);
            }
        }

        return $this;
    }
1199394
private String _serializeStruct(Struct struct, Map<Object, String> done, String id) throws ConverterException {
	StringBuilder sb = new StringBuilder(goIn() + "<STRUCT ID=\"" + id + "\">");

	Iterator<Key> it = struct.keyIterator();

	deep++;
	while (it.hasNext()) {
	    Key key = it.next();
	    // <ENTRY NAME="STRING" TYPE="STRING">hello</ENTRY>
	    String value = _serialize(struct.get(key, null), done);
	    sb.append(goIn() + "<ENTRY NAME=\"" + key.toString() + "\" TYPE=\"" + type + "\">");
	    sb.append(value);
	    sb.append(goIn() + "</ENTRY>");
	}
	deep--;

	sb.append(goIn() + "</STRUCT>");
	type = "STRUCT";
	return sb.toString();
    }
772475
public function delete( $structureOrPrimaryKeys )
    {
        if ( $structureOrPrimaryKeys instanceof Structure )
        {
            $structure = $structureOrPrimaryKeys->resetContents();
        }
        else if ( null === $structureOrPrimaryKeys ||
                is_scalar( $structureOrPrimaryKeys ) )
        {
            $structure = $this->createStructure( array(
                'rootId' => $structureOrPrimaryKeys,
            ) );
        }
        else
        {
            $structureOrPrimaryKeys = (array) $structureOrPrimaryKeys;
            $structure = $this->createStructure( array(
                'rootId' => isset( $structureOrPrimaryKeys['rootId'] )
                            ? $structureOrPrimaryKeys['rootId']
                            : reset( $structureOrPrimaryKeys )
            ) );
        }

        return $this->save( $structure );
    }
1207799
public function editFieldValue($field_id, $field_value_id = null)
    {
        $this->setFieldFieldValue($field_id);
        $this->setFieldValue($field_value_id);
        $this->setTitleEditFieldValue();
        $this->setBreadcrumbEditFieldValue();

        $this->setData('field', $this->data_field);
        $this->setData('field_value', $this->data_field_value);
        $this->setData('widget_types', $this->field->getWidgetTypes());
        $this->setData('languages', $this->language->getList(array('enabled' => true)));

        $this->submitEditFieldValue();
        $this->setDataImagesEditFieldValue();

        $this->outputEditFieldValue();
    }
1333779
public function getEditForm($id=null, $fields=null) {
        if(!$id) {
            $id=$this->currentPageID();
        }
        
        
        $record=$this->getRecord($id);
        if($record && !$record->canView()) {
            return Security::permissionFailure($this);
        }
        
        
        
        if($record) {
            $fields=$record->getCMSFields();
            $actions=new FieldList(
                                    FormAction::create('doSave', _t('CodeBank.SAVE', '_Save'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'),
                                    FormAction::create('doCancel', _t('CodeBank.CANCEL', '_Cancel'))
                                );
            
            
            if($record->canDelete()) {
                $actions->push(FormAction::create('doDelete', _t('CodeBank.DELETE', '_Delete'))->addExtraClass('ss-ui-action-destructive'));
            }
            
            
            // Use <button> to allow full jQuery UI styling
            $actionsFlattened=$actions->dataFields();
            if($actionsFlattened) {
                foreach($actionsFlattened as $action) {
                    if($action instanceof FormAction) {
                        $action->setUseButtonTag(true);
                    }
                }
            }
            
            
            if($record->hasMethod('getCMSValidator')) {
                $validator=$record->getCMSValidator();
            }else {
                $validator=new RequiredFields();
            }
            
            
            $fields->push(new HiddenField('ID', 'ID'));
            
            $form=CMSForm::create($this, 'EditForm', $fields, $actions, $validator)->setHTMLID('Form_EditForm');
            $form->loadDataFrom($record);
            $form->disableDefaultAction();
            $form->addExtraClass('cms-edit-form');
            $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
            $form->addExtraClass('center '.$this->BaseCSSClasses());
            $form->setResponseNegotiator($this->getResponseNegotiator());
            $form->setAttribute('data-pjax-fragment', 'CurrentForm');
            
            
            $this->extend('updateEditForm', $form);
            
            
            //Display message telling user to run dev/build because the version numbers are out of sync
            if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
                $form->insertBefore(new LiteralField('<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'), 'LanguageID');
            }else if($this->hasOldTables()) {
                $form->insertBefore(new LiteralField('<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'), 'LanguageID');
            }
            
            $form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: '.$this->getVersion().'</p>'));
            
            
            Requirements::javascript(CB_DIR.'/javascript/CodeBank.EditForm.js');
            
            return $form;
        }
        
        $form=$this->EmptyForm();
        if(Session::get('CodeBank.deletedSnippetID')) {
            $form->Fields()->push(new HiddenField('ID', 'ID', Session::get('CodeBank.deletedSnippetID')));
        }
        
        
        //Display message telling user to run dev/build because the version numbers are out of sync
        if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
            $form->push(new LiteralField('<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'));
        }else if($this->hasOldTables()) {
            $form->push(new LiteralField('<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'));
        }
        
        $this->redirect('admin/codeBank/');
        return $form;
    }
1085262
public static CmsEditExternalLinkDialog loadAndShowDialog(final CmsUUID structureId) {

        final CmsEditExternalLinkDialog dialog = new CmsEditExternalLinkDialog(structureId);
        CmsRpcAction<CmsExternalLinkInfoBean> action = new CmsRpcAction<CmsExternalLinkInfoBean>() {

            @Override
            public void execute() {

                CmsCoreProvider.getVfsService().loadLinkInfo(structureId, this);
            }

            @Override
            protected void onResponse(CmsExternalLinkInfoBean result) {

                dialog.initContent(result);
            }
        };
        action.execute();
        dialog.center();
        return dialog;
    }
935175
public function saveContent($id = null) {

        $id = (isset($this->request->data['id'])) ? $this->request->data['id'] : $id;
        $this->CmsContent = TableRegistry::get('CmsContent');
        $cmsContent = $this->CmsContent->get($id);

        if ($this->request->is(['patch', 'post', 'put'])) {
            $this->CmsContent->patchEntity($cmsContent, $this->request->data);

            /**
             * Upload file
             */
            $CONTENT_PATH = $this->_uploadFile($this->request->data['content_file']);
            if ($CONTENT_PATH) {
                $cmsContent->content_path = $CONTENT_PATH;
            } else {
                if ($this->request->data['content_file_remove_ck'] == 1) {
                    $this->_removeFile($cmsContent->content_path);
                    $cmsContent->content_path = '';
                }
            }

            /**
             * Save the Content
             */
            if ($this->CmsContent->save($cmsContent)) {
                $this->Flash->success('The cms content has been saved.');
                exit('ok');
            } else {
                $this->Flash->error('The cms content could not be saved. Please, try again.');
                exit('ko');
            }
        }
    }
241614
public function __async_save($navID = 0, $parentId = 0)
    {

        /** @var \samson\cms\web\navigation\CMSNav $data */
        $data = null;

        if (dbQuery('\samson\cms\web\navigation\CMSNav')->StructureID($navID)->first($data)) {
            // Update structure data
            $data->update();
        } else {
            // Create new structure
            $nav = new \samson\cms\web\navigation\CMSNav(false);
            $nav->Created = date('Y-m-d H:m:s');

            $nav->fillFields();
        }

        // return Ajax response
        return $this->__async_tree($parentId);
    }
645974
protected function lazyLoadStructure(): void
    {
        if (true === $this->structureLoaded) {
            return;
        }
        $this->structureLoaded = true;

        $messageNumber = $this->getNumber();

        $errorMessage = null;
        $errorNumber  = 0;
        \set_error_handler(static function ($nr, $message) use (&$errorMessage, &$errorNumber) {
            $errorMessage = $message;
            $errorNumber = $nr;
        });

        $structure = \imap_fetchstructure(
            $this->resource->getStream(),
            $messageNumber,
            \FT_UID
        );

        \restore_error_handler();

        if (!$structure instanceof \stdClass) {
            throw new MessageStructureException(\sprintf(
                'Message "%s" structure is empty: %s',
                $messageNumber,
                $errorMessage
            ), $errorNumber);
        }

        $this->setStructure($structure);
    }
387892
private static function buildArray(array $array, Structure $structure)
    {
        $maxKeyLength   = Util::getMaxKeyLength($array);
        $maxValueLength = Util::getMaxValueLength($array);
        $drawBorders    = ($structure->getBorder()) ? true : false;
        $insertTab      = ($structure->getTab()) ? true : false;

        if ($drawBorders) {
            $firstLine = self::printBorder($structure->getBorder(), $maxKeyLength, $maxValueLength);
            if ($insertTab) {
                $firstLine = $structure->getTab() . $firstLine;
            }
        } else {
            $firstLine = '';
        }

        $lines = '';
        foreach ($array as $key => $value) {
            $lines .= self::printStructureLine($key, $value, $structure, $maxKeyLength, $maxValueLength);
        }

        $lastLine = $firstLine;
        $result   = $firstLine . $lines . $lastLine;

        return $result;
    }
1098738
public void setStructureId(String structureId) {

        try {
            m_resourceBuilder.setStructureId(new CmsUUID(structureId));
            m_hasStructureId = true;

        } catch (Throwable e) {
            setThrowable(e);
        }

    }
474531
public void createSubEntry(final CmsClientSitemapEntry newEntry, CmsUUID parentId, CmsUUID structureId) {

        if (structureId == null) {
            structureId = m_data.getDefaultNewElementInfo().getCopyResourceId();
        }
        create(newEntry, parentId, m_data.getDefaultNewElementInfo().getId(), structureId, null, false);
    }
1113911
public function getFieldById($id, $field_name)
    {
        $data = $this->getDataById($id);
        if (null !== $data) {
            $field_name = (string)$field_name;
            if (array_key_exists($field_name, $data)) {
                return $data[$field_name];
            }
        }
        return null;
    }
1068212
public function __async_deleterelation($structure_id, $field_id)
    {
        /** @var \samson\cms\CMSNavField $relation */
        if (dbQuery('\samson\cms\CMSNavField')->FieldID($field_id)->StructureID($structure_id)->first($relation)) {
            // Delete relation
            $relation->delete();
        }

        // Return positive Ajax status
        return $this->__async_renderfields($structure_id);
    }
79274
protected function selectmultiple_button(structure $structure) {
        $buttonoptions = array(
            'type'  => 'button',
            'name'  => 'selectmultiple',
            'id'    => 'selectmultiplecommand',
            'value' => get_string('selectmultipleitems', 'quiz'),
            'class' => 'btn btn-secondary mb-1'
        );
        if (!$structure->can_be_edited()) {
            $buttonoptions['disabled'] = 'disabled';
        }

        return html_writer::tag('button', get_string('selectmultipleitems', 'quiz'), $buttonoptions);
    }