Processes the upload request
@param {array} $data Submitted data
@param {Form} $form Submitting form
@return {SS_HTTPResponse} Response
167311
public function doImportData($data, Form $form) {
        if(!Permission::check('ADMIN')) {
            Security::permissionFailure($this);
            return;
        }
        
        $fileData=$form->Fields()->dataFieldByName('ImportFile')->Value();
        //Check that the file uploaded
        if(!array_key_exists('tmp_name', $fileData) || !file_exists($fileData['tmp_name'])) {
            $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad');
            return $this->redirectBack();
        }
        
        
        //Load the file into memory
        $fileData=file_get_contents($fileData['tmp_name']);
        if($fileData===false || empty($fileData)) {
            $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad');
            return $this->redirectBack();
        }
        
        
        //Decode the json
        $fileData=json_decode($fileData);
        if($fileData===false || !is_object($fileData)) {
            $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad');
            return $this->redirectBack();
        }
        
        
        //Verify the format is ToServer
        if($fileData->format!='ToServer') {
            $form->sessionMessage(_t('CodeBank.IMPORT_FILE_FORMAT_INCORRECT', '_Import file format is incorrect'), 'bad');
            return $this->redirectBack();
        }
        
        
        //Bump Up the time limit this may take time
        set_time_limit(480);
        
        
        //Start transaction if supported
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionStart();
        }
        
        
        //If not appending empty the tables
        if(!isset($data['AppendData'])) {
            DB::query('DELETE FROM Snippet');
            DB::query('DELETE FROM SnippetVersion');
            DB::query('DELETE FROM SnippetLanguage');
            DB::query('DELETE FROM SnippetPackage');
            DB::query('DELETE FROM SnippetFolder');
        }else {
            $langMap=array();
            $pkgMap=array();
            $folderMap=array();
            $snipMap=array();
        }
        
        
        //Import Languages
        foreach($fileData->data->languages as $lang) {
            if(isset($data['AppendData'])) {
                $dbLang=SnippetLanguage::get()->filter('Name:ExactMatch:nocase', Convert::raw2sql($lang->language))->first();
                if(!empty($dbLang) && $dbLang!==false && $dbLang->ID>0) {
                    $langMap['lang-'.$lang->id]=$dbLang->ID;
                }else {
                    $newLang=new SnippetLanguage();
                    $newLang->Name=$lang->language;
                    $newLang->FileExtension=$lang->file_extension;
                    $newLang->HighlightCode=$lang->shjs_code;
                    $newLang->UserLanguage=$lang->user_language;
                    $newLang->write();
                    
                    $langMap['lang-'.$lang->id]=$newLang->ID;
                    unset($newLang);
                }
            }else {
                DB::query('INSERT INTO "SnippetLanguage" ("ID", "ClassName", "Created", "LastEdited", "Name", "FileExtension", "HighlightCode", "UserLanguage") '.
                        "VALUES(".intval($lang->id).",'SnippetLanguage', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($lang->language)."','".Convert::raw2sql($lang->file_extension)."','".Convert::raw2sql($lang->shjs_code)."',".intval($lang->user_language).")");
            }
        }
        
        
        //Import Packages
        foreach($fileData->data->packages as $pkg) {
            if(isset($data['AppendData'])) {
                $newPkg=new SnippetPackage();
                $newPkg->Title=$pkg->title;
                $newPkg->write();
                
                $pkgMap['pkg-'.$pkg->id]=$newPkg->ID;
                unset($newPkg);
            }else {
                DB::query('INSERT INTO "SnippetPackage" ("ID", "ClassName", "Created", "LastEdited", "Title") '.
                        "VALUES(".intval($pkg->id).",'SnippetPackage', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($pkg->title)."')");
            }
        }
        
        
        //Import Folders
        foreach($fileData->data->folders as $folder) {
            if(isset($data['AppendData'])) {
                if(!isset($langMap['lang-'.$folder->fkLanguageId])) {
                    if(DB::getConn()->supportsTransactions()) {
                        DB::getConn()->transactionRollback();
                    }
                    
                    $form->sessionMessage(_t('CodeBank.IMPORT_LANG_NOT_FOUND', '_Import failed language not found'), 'bad');
                    return $this->redirectBack();
                }
                
                $newFld=new SnippetFolder();
                $newFld->Name=$folder->name;
                $newFld->ParentID=($folder->fkParentId>0 && isset($folderMap['fld-'.$folder->fkParentId]) ? $folderMap['fld-'.$folder->fkParentId]:0);
                $newFld->LanguageID=$langMap['lang-'.$folder->fkLanguageId];
                $newFld->write();
                
                $folderMap['fld-'.$folder->id]=$newFld->ID;
                unset($newFld);
            }else {
                DB::query('INSERT INTO "SnippetFolder" ("ID", "ClassName", "Created", "LastEdited", "Name", "ParentID", "LanguageID") '.
                        "VALUES(".intval($folder->id).",'SnippetFolder', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($folder->name)."', ".intval($folder->fkParentId).", ".intval($folder->fkLanguageId).")");
            }
        }
        
        
        //Import Snippets
        foreach($fileData->data->snippets as $snip) {
            if(isset($data['AppendData'])) {
                if(!isset($langMap['lang-'.$snip->fkLanguage])) {
                    if(DB::getConn()->supportsTransactions()) {
                        DB::getConn()->transactionRollback();
                    }
                    
                    $form->sessionMessage(_t('CodeBank.IMPORT_LANG_NOT_FOUND', '_Import failed language not found'), 'bad');
                    return $this->redirectBack();
                }
                
                $newSnip=new Snippet();
                $newSnip->Title=$snip->title;
                $newSnip->Description=$snip->description;
                $newSnip->Tags=$snip->tags;
                $newSnip->LanguageID=$langMap['lang-'.$snip->fkLanguage];
                $newSnip->CreatorID=Member::currentUserID();
                $newSnip->LastEditorID=Member::currentUserID();
                $newSnip->PackageID=($snip->fkPackageID>0 && isset($pkgMap['pkg-'.$snip->fkPackageID]) ? $pkgMap['pkg-'.$snip->fkPackageID]:0);
                $newSnip->FolderID=($snip->fkFolderID>0 && isset($folderMap['fld-'.$snip->fkFolderID]) ? $folderMap['fld-'.$snip->fkFolderID]:0);
                $newSnip->write();
                
                $snipMap['snip-'.$snip->id]=$newSnip->ID;
                unset($newSnip);
            }else {
                DB::query('INSERT INTO "Snippet" ("ID", "ClassName", "Created", "LastEdited", "Title", "Description", "Tags", "LanguageID", "CreatorID", "LastEditorID", "PackageID", "FolderID") '.
                        "VALUES(".intval($snip->id).",'Snippet', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($snip->title)."', '".Convert::raw2sql($snip->description)."', '".Convert::raw2sql($snip->tags)."', ".intval($snip->fkLanguage).", ".Member::currentUserID().", ".Member::currentUserID().", ".intval($snip->fkPackageID).", ".intval($snip->fkFolderID).")");
            }
        }
        
        
        //Import Snippet Versions
        foreach($fileData->data->versions as $ver) {
            if(isset($data['AppendData'])) {
                if(!isset($snipMap['snip-'.$ver->fkSnippit])) {
                    if(DB::getConn()->supportsTransactions()) {
                        DB::getConn()->transactionRollback();
                    }
                
                    $form->sessionMessage(_t('CodeBank.IMPORT_SNIP_NOT_FOUND', '_Import failed snippet not found'), 'bad');
                    return $this->redirectBack();
                }
                
                DB::query('INSERT INTO "SnippetVersion" ("ClassName", "Created", "LastEdited", "Text", "ParentID") '.
                        "VALUES('SnippetVersion', '".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->text)."', ".intval($snipMap['snip-'.$ver->fkSnippit]).")");
            }else {
                DB::query('INSERT INTO "SnippetVersion" ("ID", "ClassName", "Created", "LastEdited", "Text", "ParentID") '.
                        "VALUES(".intval($ver->id).",'SnippetVersion', '".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->text)."', ".intval($ver->fkSnippit).")");
            }
        }
        
        
        //End transaction if supported
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionEnd();
        }
        
        
        //Display success after redirecting back
        Session::set('reloadOnImportDialogClose', true);
        $form->sessionMessage(_t('CodeBank.IMPORT_COMPLETE', '_Import Completed'), 'good');
        return $this->redirectBack();
    }
270956
public function handleUpload(SS_HTTPRequest $request)
    {
        $request->setUrl('upload');

        /** @var Folder $folder */
        $folder = Folder::get()->byID($request->param('FolderID'));

        /** @var FileAttachmentField $uploader */
        $uploader = FileAttachmentField::create('dummy');

        if ($folder) {
            $uploader->setFolderName(self::remove_assets_dir($folder->Filename));
        } else {
            $uploader->setFolderName('/');
        }

        /** @var SS_HTTPResponse $httpResponse */
        $httpResponse = $uploader->handleRequest($request, DataModel::inst());

        if ($httpResponse->getStatusCode() !== 200) {
            return $httpResponse;
        }

        $ids = $httpResponse->getBody();
        $files = File::get()->byIDs(explode(',', $ids));
        $result = array();

        foreach ($files as $f) {
            $result[] = $this->createFileJson($f, $folder);
        }

        $response = new SS_HTTPResponse(
            Convert::array2json($result), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
653448
public function doUpdate($data, $form)
    {
        foreach ($this->items as $cart_item) {
            foreach ($data as $key => $value) {
                $sliced_key = explode("_", $key);
                if ($sliced_key[0] == "Quantity") {
                    if (isset($cart_item) && ($cart_item->Key == $sliced_key[1])) {
                        try {
                            if ($value > 0) {
                                $this->update($cart_item->Key, $value);
                                
                                $this->setSessionMessage(
                                    "success",
                                    _t("Checkout.UpdatedShoppingCart", "Shopping cart updated")
                                );
                            } else {
                                $this->remove($cart_item->Key);
                                
                                $this->setSessionMessage(
                                    "success",
                                    _t("Checkout.EmptiedShoppingCart", "Shopping cart emptied")
                                );
                            }
                        } catch (ValidationException $e) {
                            $this->setSessionMessage(
                                "bad",
                                $e->getMessage()
                            );
                        } catch (Exception $e) {
                            $this->setSessionMessage(
                                "bad",
                                $e->getMessage()
                            );
                        }
                    }
                }
            }
        }

        $this->save();

        return $this->redirectBack();
    }
454001
public function archive($data, $form)
    {
        $id = $data['ID'];
        /** @var SiteTree $record */
        $record = SiteTree::get()->byID($id);
        if (!$record || !$record->exists()) {
            throw new HTTPResponse_Exception("Bad record ID #$id", 404);
        }
        if (!$record->canArchive()) {
            return Security::permissionFailure();
        }

        // Archive record
        $record->doArchive();

        $this->getResponse()->addHeader(
            'X-Status',
            rawurlencode(_t(
                __CLASS__ . '.ARCHIVEDPAGE',
                "Archived page '{title}'",
                ['title' => $record->Title]
            ))
        );

        // Even if the record has been deleted from stage and live, it can be viewed in "archive mode"
        return $this->getResponseNegotiator()->respond($this->getRequest());
    }
1148598
public function renderFormAction(
        Action $action,
        Request $request,
        FormInterface $form,
        $data = null,
        array $viewParameters = []
    ): Response {
        $viewParameters = array_merge($this->getViewParameters($action, $request, $form, $data), $viewParameters);

        return $this->renderAction($action, $viewParameters);
    }
1064527
public function delete($data, $form)
    {
        $id = $data['ID'];
        $record = SiteTree::get()->byID($id);
        if ($record && !$record->canDelete()) {
            return Security::permissionFailure();
        }
        if (!$record || !$record->ID) {
            throw new HTTPResponse_Exception("Bad record ID #$id", 404);
        }

        // Delete record
        $record->delete();

        $this->getResponse()->addHeader(
            'X-Status',
            rawurlencode(_t(
                __CLASS__ . '.REMOVEDPAGEFROMDRAFT',
                "Removed '{title}' from the draft site",
                ['title' => $record->Title]
            ))
        );

        // Even if the record has been deleted from stage and live, it can be viewed in "archive mode"
        return $this->getResponseNegotiator()->respond($this->getRequest());
    }
268078
public function doRestore($data, $form)
    {
        $record = $this->owner->getRecord();

        $message = RestoreAction::restore($record);

        $controller = $this->owner->popupController;
        $controller->getRequest()->addHeader('X-Pjax', 'Content');
        $controller->getEditForm()->sessionMessage($message['text'], $message['type'], ValidationResult::CAST_HTML);

        return $controller->redirect($controller->Link(), 'index');
    }
1263301
public function doPrevious($data, $form)
    {
        $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content');
        $link = $this->getEditLink($this->getPreviousRecordID());
        return $this->redirect($link);
    }
565823
public function doSave($data, $form)
    {
        $recordType = $this->getRecordType();
        $record = $recordType::create();
        $form->saveInto($record);
        $record->write();
        $this->redirect($this->Link());
    }
1123819
public function submitted(Form $form)
	{
		if (!isset($form['group_action']['submit']) || !$form['group_action']['submit']->isSubmittedBy()) {
			return;
		}

		$values = $form->getValues();
		$values = $values['group_action'];

		if ($values->group_action === 0 || $values->group_action === null) {
			return;
		}

		/**
		 * @todo Define items IDs
		 */
		$http_ids = $form->getHttpData(Form::DATA_LINE | Form::DATA_KEYS, strtolower($this->datagrid->getName()) . '_group_action_item[]');
		$ids = array_keys($http_ids);

		$id = $values->group_action;
		$this->group_actions[$id]->onSelect($ids, isset($values->{$id}) ? $values->{$id} : null);

		$form['group_action']['group_action']->setValue(null);
	}
174900
public function doRegister($data, $form)
    {
        $r = new EventRegistration();
        $form->saveInto($r);
        $r->write();

        return "Thanks. We've received your registration.";
    }
1340690
public function process(Request $request, FormInterface $form)
    {
        if ($request->isMethod('POST')) {
            $form->submit($request);
            if ($form->isValid()) {
                return true;
            }
        }

        return false;
    }
571518
public function doPostComment($data, $form)
    {
        // Load class and parent from data
        if (isset($data['ParentClassName'])) {
            $this->controller->setParentClass($data['ParentClassName']);
        }
        if (isset($data['ParentID']) && ($class = $this->controller->getParentClass())) {
            $this->controller->setOwnerRecord($class::get()->byID($data['ParentID']));
        }
        if (!$this->controller->getOwnerRecord()) {
            return $this->getRequestHandler()->httpError(404);
        }

        // cache users data
        $form->setSessionData([
            'UserData' => json_encode($data),
            'Comment' =>  $data['Comment']
        ]);

        // extend hook to allow extensions. Also see onAfterPostComment
        $this->controller->extend('onBeforePostComment', $form);

        // If commenting can only be done by logged in users, make sure the user is logged in
        if (!$this->controller->getOwnerRecord()->canPostComment()) {
            return Security::permissionFailure(
                $this->controller,
                _t(
                    'SilverStripe\\Comments\\Controllers\\CommentingController.PERMISSIONFAILURE',
                    "You're not able to post comments to this page. Please ensure you are logged in and have an "
                    . 'appropriate permission level.'
                )
            );
        }

        if ($member = Security::getCurrentUser()) {
            $form->Fields()->push(HiddenField::create('AuthorID', 'Author ID', $member->ID));
        }

        // What kind of moderation is required?
        switch ($this->controller->getOwnerRecord()->ModerationRequired) {
            case 'Required':
                $requireModeration = true;
                break;
            case 'NonMembersOnly':
                $requireModeration = empty($member);
                break;
            case 'None':
            default:
                $requireModeration = false;
                break;
        }

        $comment = Comment::create();
        $form->saveInto($comment);

        $comment->ParentID = $data['ParentID'];
        $comment->ParentClass = $data['ParentClassName'];

        $comment->AllowHtml = $this->controller->getOption('html_allowed');
        $comment->Moderated = !$requireModeration;

        // Save into DB, or call pre-save hooks to give accurate preview
        $usePreview = $this->controller->getOption('use_preview');
        $isPreview = $usePreview && !empty($data['IsPreview']);
        if ($isPreview) {
            $comment->extend('onBeforeWrite');
        } else {
            $comment->write();

            // extend hook to allow extensions. Also see onBeforePostComment
            $this->controller->extend('onAfterPostComment', $comment);
        }

        // we want to show a notification if comments are moderated
        if ($requireModeration && !$comment->IsSpam) {
            $this->getRequest()->getSession()->set('CommentsModerated', 1);
        }

        // clear the users comment since the comment was successful.
        if ($comment->exists()) {
            // Remove the comment data as it's been saved already.
            unset($data['Comment']);
        }

        // cache users data (name, email, etc to prepopulate on other forms).
        $form->setSessionData([
            'UserData' => json_encode($data),
        ]);

        // Find parent link
        if (!empty($data['ReturnURL'])) {
            $url = $data['ReturnURL'];
        } elseif ($parent = $comment->Parent()) {
            $url = $parent->Link();
        } else {
            return $this->controller->redirectBack();
        }

        // Given a redirect page exists, attempt to link to the correct anchor
        if ($comment->IsSpam) {
            // Link to the form with the error message contained
            $hash = $form->FormName();
        } elseif (!$comment->Moderated) {
            // Display the "awaiting moderation" text
            $hash = 'moderated';
        } else {
            // Link to the moderated, non-spam comment
            $hash = $comment->Permalink();
        }

        return $this->controller->redirect(Controller::join_links($url, "#{$hash}"));
    }
273703
function _process_submission($method) {
        $submission = array();
        if (!empty($this->_ajaxformdata)) {
            $submission = $this->_ajaxformdata;
        } else if ($method == 'post') {
            if (!empty($_POST)) {
                $submission = $_POST;
            }
        } else {
            $submission = $_GET;
            merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
        }

        // following trick is needed to enable proper sesskey checks when using GET forms
        // the _qf__.$this->_formname serves as a marker that form was actually submitted
        if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
            if (!confirm_sesskey()) {
                print_error('invalidsesskey');
            }
            $files = $_FILES;
        } else {
            $submission = array();
            $files = array();
        }
        $this->detectMissingSetType();

        $this->_form->updateSubmission($submission, $files);
    }
879731
protected function pushSecondaryKeys($data, $form)
    {
        if (isset($data[$form]) && is_array($data[$form])) {
            foreach ($data[$form] as $secondaryKey => $values) {
                $data[$form][$secondaryKey][$this->relSecondaryKey] = $secondaryKey;
            }
        }

        return $data;
    }
331689
public function submit(Form $form)
    {
        return $this->request($form->getUri(), $form->getMethod(), $form->getPhpValues(), $form->getPhpFiles());
    }
1359903
public function save($data, $form) {
		if (!$this->data()->canEdit()) {
			return Security::permissionFailure($this);
		}

		$existing = $this->getEditingLocks($this->data(), true);
		// oops, we've somehow got here even though we shouldn't have
		if ($existing && $existing['user'] != Member::currentUser()->Email) {
			return "Someone somehow locked it while you were gone, this shouldn't happen like this :(";
		}

		$this->savePage($this->data(), $form);
		if (WikiPage::$auto_publish) {
			// do publish
			$this->data()->doPublish();
		}

		return $this->redirect($this->data()->Link('edit') . '?stage=Stage');
	}