function submitFeedback(array $data, Form $form) { // TRUE if the submission contains a link. Crude spam mitigation. $ContainsLink = strpos($data['Content'], "http://") !== false; if ($data['Content'] != NULL && !$ContainsLink) { $FeedbackSubmission = new FeedbackSubmission(); $form->saveInto($FeedbackSubmission); // Tie the URL of the current page to the feedback submission $page = Director::get_current_page(); $FeedbackSubmission->Page = $page->Link(); //$FeedbackSubmission->write(); //Send email alert about submission $Subject = "New Website Feedback Submission"; $email = EmailFactory::getInstance()->buildEmail(FEEDBACK_FORM_FROM_EMAIL, FEEDBACK_FORM_TO_EMAIL, $Subject); $email->setTemplate("FeedbackSubmissionEmail"); $email->populateTemplate($FeedbackSubmission); $email->send(); // Redirect back to the page with a success message $form->controller->setMessage('Success', 'Thanks for providing feedback to improve the OpenStack website!'); $form->controller->redirectBack(); } else { $form->controller->setMessage('Error', "Oops! It doesn't look like you provided any feedback. Please check the form and try again."); $form->controller->redirectBack(); } }
/** * Update a workflow based on user input. * * @todo refactor with WorkflowInstance::updateWorkflow * * @param array $data * @param Form $form * @param SS_HTTPRequest $request * @return String */ public function updateworkflow($data, Form $form, $request) { $svc = singleton('WorkflowService'); $p = $form->getRecord(); $workflow = $svc->getWorkflowFor($p); $action = $workflow->CurrentAction(); if (!$p || !$p->canEditWorkflow()) { return; } $allowedFields = $workflow->getWorkflowFields()->saveableFields(); unset($allowedFields['TransitionID']); $allowed = array_keys($allowedFields); if (count($allowed)) { $form->saveInto($action, $allowed); $action->write(); } if (isset($data['TransitionID']) && $data['TransitionID']) { $svc->executeTransition($p, $data['TransitionID']); } else { // otherwise, just try to execute the current workflow to see if it // can now proceed based on user input $workflow->execute(); } return $this->owner->getResponseNegotiator()->respond($this->owner->getRequest()); }
public function Register($data, Form $form) { if (!Member::currentUser()) { $member = new Member(); // Debug::show($form); $form->saveInto($member); if (Group::get()->filter('Title', 'Subscribed')->count() == 0) { $group = Group::create(); $group->Title = 'Subscribed'; $group->write(); } else { $group = Group::get()->filter('Title', 'Subscribed')->First(); } if (Member::get()->filter('Email', $data['Email'])) { $form->addErrorMessage('Email', 'That email address is already in use. <a href="Security/login">login</a>', 'bad', true, true); //Controller::curr()->redirect('register'); } else { //has to be called before setting group $member->write(); if (!$member->inGroup($group)) { $member->Groups()->add($group); } } } Controller::curr()->redirectBack(); }
/** * Form action handler for ContactInquiryForm. * * @param array $data The form request data submitted * @param Form $form The {@link Form} this was submitted on */ function dosave(array $data, Form $form, SS_HTTPRequest $request) { $SQLData = Convert::raw2sql($data); $attrs = $form->getAttributes(); if ($SQLData['Comment'] != '' || $SQLData['Url'] != '') { // most probably spam - terminate silently Director::redirect(Director::baseURL() . $this->URLSegment . "/success"); return; } $item = new ContactInquiry(); $form->saveInto($item); // $form->sessionMessage(_t("ContactPage.FORMMESSAGEGOOD", "Your inquiry has been submitted. Thanks!"), 'good'); $item->write(); $mailFrom = $this->currController->MailFrom ? $this->currController->MailFrom : $SQLData['Email']; $mailTo = $this->currController->MailTo ? $this->currController->MailTo : Email::getAdminEmail(); $mailSubject = $this->currController->MailSubject ? $this->currController->MailSubject . ' - ' . $SQLData['Ref'] : _t('ContactPage.SUBJECT', '[web] New contact inquiry - ') . ' ' . $data['Ref']; $email = new Email($mailFrom, $mailTo, $mailSubject); $email->replyTo($SQLData['Email']); $email->setTemplate("ContactInquiry"); $email->populateTemplate($SQLData); $email->send(); // $this->controller->redirectBack(); if ($email->send()) { $this->controller->redirect($this->controller->Link() . "success"); } else { $this->controller->redirect($this->controller->Link() . "error"); } return false; }
function doRegister($data, Form $form) { //Check for existing member email address if ($member = DataObject::get_one("Member", "`Email` = '" . Convert::raw2sql($data['Email']) . "'")) { //Set error message $form->sessionMessage($data['Email'] . ". Sorry, that email address already exists. Please choose another.", 'bad'); //Return back to form return $this->redirectBack(); //return Director::redirectBack(); } else { //Otherwise create new member and log them in $Member = new Member(); $form->saveInto($Member); $Member->write(); $Member->login(); //Find or create the 'user' group if (!($userGroup = DataObject::get_one('Group', "Code = 'users'"))) { $userGroup = new Group(); $userGroup->Code = "users"; $userGroup->Title = "users"; $userGroup->Write(); $userGroup->Members()->add($Member); } //Add member to user group $userGroup->Members()->add($Member); //Get profile page if ($ProfilePage = DataObject::get_one('EditProfilePage')) { //echo "profile page exists"; //Redirect to profile page with success message return $this->redirect($ProfilePage->Link()); } } }
/** * * @param Form $form * @return SignatureRecord */ protected function updateRecord(Form $form) { $signature = $this->getSignatureRecord(true); $form->saveInto($signature); $signature->write(); return $signature; }
/** * Save the current sites {@link SiteConfig} into the database * * @param array $data * @param Form $form * @return String */ public function save_siteconfig($data, $form) { $siteConfig = SiteConfig::current_site_config(); $form->saveInto($siteConfig); $siteConfig->write(); $this->response->addHeader('X-Status', rawurlencode(_t('LeftAndMain.SAVEDUP', 'Saved.'))); return $this->getResponseNegotiator()->respond($this->request); }
/** * Save the current sites {@link SiteConfig} into the database * * @param array $data * @param Form $form * @return String */ function save_siteconfig($data, $form) { $siteConfig = SiteConfig::current_site_config(); $form->saveInto($siteConfig); $siteConfig->write(); $this->response->addHeader('X-Status', rawurlencode(_t('LeftAndMain.SAVEDUP', 'Saved.'))); return $form->forTemplate(); }
public function testFormSaveInto() { $form = new Form(new Controller(), 'Form', new FieldList($f = new DatetimeField('MyDatetime', null)), new FieldList(new FormAction('doSubmit'))); $f->setValue(array('date' => '29/03/2003', 'time' => '23:59:38')); $m = new DatetimeFieldTest_Model(); $form->saveInto($m); $this->assertEquals('2003-03-29 23:59:38', $m->MyDatetime); }
/** * Handles adding the snippet to the database * @param {array} $data Data submitted by the user * @param {Form} $form Form submitted */ public function doAdd($data, Form $form) { $record = $this->getRecord(null); $form->saveInto($record); $record->write(); $editController = singleton('CodeBank'); $editController->setCurrentPageID($record->ID); return $this->redirect(Controller::join_links(singleton('CodeBank')->Link('show'), $record->ID)); }
/** * @param array $data * @param Form $form * @throws ValidationException * @throws null */ public function HandleForm($data, $form) { /** @var Contact $Contact */ $Contact = Contact::create(); $form->saveInto($Contact); $Contact->write(); Session::set('ThanksMessage', true); $this->redirect($this->Link() . '#section-contact'); }
function doSubmit(array $raw_data, Form $form) { $controller = $form->getController(); $data = Convert::raw2sql($raw_data); $submission = new Distributor(); $form->saveInto($submission); $submission->DistributorPageID = $controller->ID; $submission->write(); return $controller->redirect($controller->Link()); }
public function testLookupFieldDisabledSaving() { $object = new DataObjectTest_Team(); $form = new Form(new Controller(), 'Form', new FieldList(new LookupField('Players', 'Players')), new FieldList()); $form->loadDataFrom(array('Players' => array(14, 18, 22))); $form->saveInto($object); $playersIds = $object->Players()->getIDList(); $this->assertTrue($form->validate()); $this->assertEquals($playersIds, array(), 'saveInto() should not save into the DataObject for the LookupField'); }
/** * Relation auto-setting is now the only option */ function testAutoRelationSettingOn() { $o = new TableFieldTest_Object(); $o->write(); $tf = new TableField('HasManyRelations', 'TableFieldTest_HasManyRelation', array('Value' => 'Value'), array('Value' => 'TextField')); // Test with auto relation setting $form = new Form(new TableFieldTest_Controller(), "Form", new FieldList($tf), new FieldList()); $form->loadDataFrom($o); $tf->setValue(array('new' => array('Value' => array('one', 'two')))); $form->saveInto($o); $this->assertEquals(2, $o->HasManyRelations()->Count()); }
/** * Updates an existing Member's profile. */ public function save(array $data, Form $form) { $form->saveInto($this->member); try { $this->member->write(); } catch (ValidationException $e) { $form->sessionMessage($e->getResult()->message(), 'bad'); return $this->redirectBack(); } $form->sessionMessage(_t('MemberProfiles.PROFILEUPDATED', 'Your profile has been updated.'), 'good'); return $this->redirectBack(); }
/** * Save the changes to the form, and redirect to the checkout page * * @param array $data * @param Form $form * @param SS_HTTPRequest $request * * @return bool|SS_HTTPResponse */ public function proceed($data, $form, $request) { $member = Member::currentUser(); if (!$member) { return false; } $form->saveInto($member); $member->write(); $form->sessionMessage(_t("MemberForm.DetailsSaved", 'Your details have been saved'), 'good'); $this->extend('updateShopAccountFormResponse', $request, $form, $data, $response); return $response ?: $this->getController()->redirect(CheckoutPage::find_link()); }
/** * Save the current sites {@link SiteConfig} into the database * * @param array $data * @param Form $form * @return String */ public function save_siteconfig($data, $form) { $siteConfig = SiteConfig::current_site_config(); $form->saveInto($siteConfig); try { $siteConfig->write(); } catch (ValidationException $ex) { $form->sessionMessage($ex->getResult()->message(), 'bad'); return $this->getResponseNegotiator()->respond($this->request); } $this->response->addHeader('X-Status', rawurlencode(_t('LeftAndMain.SAVEDUP', 'Saved.'))); return $this->getResponseNegotiator()->respond($this->request); }
/** * Handles validating the final step and writing the tickets data to the * registration object. */ public function finish($data, $form) { parent::finish($data, $form); $step = $this->getCurrentStep(); $datetime = $this->getController()->getDateTime(); $registration = $this->session->getRegistration(); $ticketsStep = $this->getSavedStepByClass('EventRegisterTicketsStep'); $tickets = $ticketsStep->loadData(); // Check that the requested tickets are still available. if (!$this->validateTickets($tickets['Tickets'], $form)) { Session::set("FormInfo.{$form->FormName()}.data", $form->getData()); Director::redirectBack(); return false; } // Validate the final step. if (!$step->validateStep($data, $form)) { Session::set("FormInfo.{$form->FormName()}.data", $form->getData()); Director::redirectBack(); return false; } // Reload the first step fields into a form, then save it into the // registration object. $ticketsStep->setForm($form); $fields = $ticketsStep->getFields(); $form = new Form($this, '', $fields, new FieldSet()); $form->loadDataFrom($tickets); $form->saveInto($registration); if ($member = Member::currentUser()) { $registration->Name = $member->getName(); $registration->Email = $member->Email; } $registration->TimeID = $datetime->ID; $registration->MemberID = Member::currentUserID(); $total = $ticketsStep->getTotal(); $registration->Total->setCurrency($total->getCurrency()); $registration->Total->setAmount($total->getAmount()); foreach ($tickets['Tickets'] as $id => $quantity) { if ($quantity) { $registration->Tickets()->add($id, array('Quantity' => $quantity)); } } $registration->write(); $this->session->delete(); // If the registrations is already valid, then send a details email. if ($registration->Status == 'Valid') { EventRegistrationDetailsEmail::factory($registration)->send(); } $this->extend('onRegistrationComplete', $registration); return Director::redirect(Controller::join_links($datetime->Event()->Link(), 'registration', $registration->ID, '?token=' . $registration->Token)); }
public function doRegisterPersonal(array $data, Form $form) { $exist = Member::get()->filter(array('Email' => $this->Email))->first(); if ($exist) { $form->sessionMessage('该电子邮件已被注册', 'bad'); return $this->redirectBack(); } $member = new UnapprovedMember(); $form->saveInto($member); $member->setField('MemberType', 'Personal'); $member->write(); $form->sessionMessage('注册成功,请等待您所属的企业审核账号,审核通过之后可以正常登陆', 'good'); return $this->redirectBack(); }
public function add(array $data, Form $form, $request) { if (!$this->context && isset($data['TargetType'])) { $this->context = DataObject::get_by_id($data['TargetType'], $data['TargetID']); } if (!$this->context->canEdit()) { return; } $comment = new InlineComment(); $form->saveInto($comment); $comment->AuthorID = Member::currentUserID(); $comment->write(); $res = array('comment' => $comment->toMap()); return singleton('ICUtils')->ajaxResponse($res, true); }
/** * Process the submitted form data and save to database * * @return Redirect */ public function post(array $data, Form $form) { $discussion = null; $page = DiscussionHolder::get()->byID($this->controller->ID); $member = Member::currentUser(); if ($this->controller->canStartDiscussions($member)) { // Check if we are editing or creating if (isset($data['ID']) && $data['ID']) { $discussion = Discussion::get()->byID($data['ID']); } if (!$discussion || $discussion == null) { $discussion = Discussion::create(); } $form->saveInto($discussion); $discussion->AuthorID = $member->ID; $discussion->ParentID = $page->ID; $form->saveInto($discussion); $discussion->write(); $discussion_url = Controller::join_links($this->controller->Link("view"), $discussion->ID); return $this->controller->redirect($discussion_url); } else { return $this->controller->httpError(404); } }
/** * Process payment form and return next step in the payment process. * Steps taken are: * 1. create new payment * 2. save form into payment * 3. return payment result * * @param Order $order - the order that is being paid * @param Form $form - the form that is being submitted * @param Array $data - Array of data that is submittted * @return Boolean - if successful, this method will return TRUE */ public static function process_payment_form_and_return_next_step($order, $form, $data) { if (!$order) { $form->sessionMessage(_t('EcommercePayment.NOORDER', 'Order not found.'), 'bad'); Director::redirectBack(); return false; } $paidBy = $order->Member(); if (!$paidBy) { $paidBy = Member::currentUser(); } $paymentClass = !empty($data['PaymentMethod']) ? $data['PaymentMethod'] : null; $payment = class_exists($paymentClass) ? new $paymentClass() : null; if (!($payment && $payment instanceof Payment)) { $form->sessionMessage(_t('EcommercePayment.NOPAYMENTOPTION', 'No Payment option selected.'), 'bad'); Director::redirectBack(); return false; } // Save payment data from form and process payment $form->saveInto($payment); $payment->OrderID = $order->ID; if (is_object($paidBy)) { $payment->PaidByID = $paidBy->ID; } $payment->Amount = $order->TotalOutstandingAsMoneyObject(); $payment->write(); // Process payment, get the result back $result = $payment->processPayment($data, $form); if (!$result instanceof Payment_Result) { return false; } else { if ($result->isProcessing()) { //IMPORTANT!!! // isProcessing(): Long payment process redirected to another website (PayPal, Worldpay) //redirection is taken care of by payment processor return $result->getValue(); } else { //payment is done, redirect to either returntolink //OR to the link of the order .... if (isset($data["returntolink"])) { Director::redirect($data["returntolink"]); } else { Director::redirect($order->Link()); } } return true; } }
/** * * Action called by the form to actually create a new page object. * * @param SS_HttpRequest $request * @param Form $form */ public function createpage($request, Form $form) { // create a new object and bind the form data $pid = $this->CreateLocation()->ID; if (!$pid) { $pid = 0; } $type = $this->CreateType; $obj = new $type(); $form->saveInto($obj); $obj->ParentID = $pid; Versioned::reading_stage('Stage'); $obj->write('Stage'); // redirect to the created object Director::redirect($obj->Link() . '?stage=Stage'); }
/** * Register a new member * * @param array $data User submitted data * @param Form $form The used form */ function doSaveNotificationSettings($data, $form) { $filter = array(); $member = Member::get()->byID($data["ID"]); // Check that a mamber isn't trying to mess up another users profile if (Member::currentUserID() && $member->canEdit(Member::currentUser())) { // Save member $form->saveInto($member); $member->write(); $this->owner->setSessionMessage("message success", _t("Discussions.NotificationSettingsUpdated", "Notification settings updated")); return $this->owner->redirect($this->owner->Link()); } else { $this->owner->setSessionMessage("message error", _t("Discussions.CannotEditAccount", "You cannot edit this account")); } return $this->owner->redirectBack(); }
/** * Store it. * And also check if it's no double-post. Limited to 60 seconds, but it can be differed. * I wonder if this is XSS safe? The saveInto does this for me, right? * @param array $data Posted data as array * @param Form $form FormObject containing the entire Form as an Object. */ public function CommentStore($data, $form) { /** * If the "Extra" field is filled, we have a bot. * Also, the nsas (<noscript> Anti Spam) is a bot. Bot's don't use javascript. * Note, a legitimate visitor that has JS disabled, will be unable to post! */ if (!isset($data['Extra']) || $data['Extra'] == '' || isset($data['nsas'])) { $data['Comment'] = Convert::raw2sql($data['Comment']); $exists = Comment::get()->filter(array('Comment:PartialMatch' => $data['Comment']))->where('ABS(TIMEDIFF(NOW(), Created)) < 60'); if (!$exists->count()) { $comment = Comment::create(); $form->saveInto($comment); $comment->NewsID = $data['NewsID']; $comment->write(); } } Controller::curr()->redirectBack(); }
public function postEntry(array $data, Form $form) { if (!empty($data['Website'])) { if (!filter_var($data['Website'], FILTER_VALIDATE_URL)) { $form->addErrorMessage('Website', _t('GuestbookController.INVALIDWEBSITEFORMAT', "Invalid format for website."), 'bad'); return $this->redirectBack(); } } if (Session::get("GuestbookPosted") > time() - $this->FloodLimit) { $floodMessage = _t('GuestbookController.FLOODLIMITEXCEEDED', "You have already posted the last {seconds} seconds. Please wait.", "", $this->FloodLimit); $form->sessionMessage($floodMessage, 'bad'); return $this->redirectBack(); } $entry = GuestbookEntry::create(); $entry->GuestbookID = $this->ID; $form->saveInto($entry); $entry->write(); $form->sessionMessage(_t('GuestbookController.ENTRYSAVED', "Entry has been saved."), 'good'); Session::set('GuestbookPosted', time()); return $this->redirectBack(); }
public function save(array $data, Form $form, SS_HTTPRequest $request) { $obj = $this->getContextObject(); if (!$obj) { throw new Exception('Context Object Not Found'); } //Only Save data when Transition is 'Active' if ($this->getCurrentTransition()->Type == 'Active') { if ($obj->canEdit()) { $form->saveInto($obj); $obj->write(); } } //run execute on instance $action = $this->contextObj->getWorkflowInstance()->currentAction(); $action->BaseAction()->execute($this->contextObj->getWorkflowInstance()); //get valid transitions $transitions = $action->getValidTransitions(); //tell instance to execute transition if ($transitions->find('ID', $this->transitionID)) { $this->contextObj->getWorkflowInstance()->performTransition($this->getCurrentTransition()); } $this->redirect($this->contextObj->EditLink()); }
/** * Postback action to save a record * * @param array $data * @param Form $form * @param SS_HTTPRequest $request * @return mixed */ function doSave($data, $form, $request) { $form->saveInto($this->currentRecord); try { $this->currentRecord->write(); } catch (ValidationException $e) { $form->sessionMessage($e->getResult()->message(), 'bad'); } // Behaviour switched on ajax. if (Director::is_ajax()) { return $this->edit($request); } else { Director::redirectBack(); } }
/** * @param array $data * @param Form $form * * @return SS_HTTPResponse */ public function doPostSnapshot($data, $form) { $this->setCurrentActionType(self::ACTION_SNAPSHOT); $project = $this->getCurrentProject(); if (!$project) { return $this->project404Response(); } $validEnvs = $project->DNEnvironmentList()->filterByCallback(function ($item) { return $item->canUploadArchive(); }); // Validate $data['EnvironmentID'] by checking against $validEnvs. $environment = $validEnvs->find('ID', $data['EnvironmentID']); if (!$environment) { throw new LogicException('Invalid environment'); } $dataArchive = DNDataArchive::create(array('UploadToken' => DNDataArchive::generate_upload_token())); $form->saveInto($dataArchive); $dataArchive->write(); return $this->redirect(Controller::join_links($project->Link(), 'postsnapshotsuccess', $dataArchive->ID)); }
/** * @param array $data * @param Form $form * @param SS_HTTPRequest $request */ public function doEdit(array $data, Form $form, SS_HTTPRequest $request) { // Check form field state if ($this->parent->isDisabled() || $this->parent->isReadonly()) { return $this->httpError(403); } // Check item permissions $item = $this->getItem(); if (!$item) { return $this->httpError(404); } if ($item instanceof Folder) { return $this->httpError(403); } $memberID = Member::currentUserID(); $res = false; try { // Owner can always delete if ($memberID && $item->OwnerID == $memberID) { $res = true; } else { $res = $item->canEditFrontend(); } } catch (Exception $ex) { } $form->saveInto($item); $item->write(); $form->sessionMessage(_t('UploadField.Saved', 'Saved'), 'good'); return $this->edit($request); }