/** * @param SS_HTTPRequest $req * @return HTMLText */ public function zip(SS_HTTPRequest $req) { $orderID = (int) $req->postVar('OrderID'); $hashes = $req->postVar('Files'); $files = array(); // check inputs - should we respond more intelligently if they just didn't check anything? if (empty($hashes)) { $this->httpError(404); } // grab a list of file objects foreach ($hashes as $hash) { $link = DownloadLink::get_by_hash($hash); if ($link && $link->exists()) { $file = $link->File(); if ($file && $file->exists()) { $files[] = $file; } } } if (count($files) == 0) { $this->httpError(404); } // display a temporary loading page and start processing the zip return $this->initiateOfflineProcessing($files, $orderID); }
public function register(SS_HTTPRequest $request) { if ($request->isPOST()) { try { if (Customer::get()->filter('Email', $request->postVar('Email'))->count()) { throw new ValidationException("Sorry a member with that email address already exists"); } $password = Customer::create_new_password(); /** @var Customer $member */ $member = Injector::inst()->create('ProfiledMemberClass'); $member->changePassword($password); // update member with cleansed posted variables $updateData = array_merge(ProfiledMemberForm::update_models('register', array_merge($request->postVars(), ['Password' => $password]), $member)); /** @var CryptofierImplementation $crypto */ $crypto = Injector::inst()->get('CryptofierService'); $token = $crypto->friendly($crypto->encrypt($member->Email)); $member->{ProfiledMemberExtension::VerificationFieldName} = $token; $member->write(); $member->addToGroupByCode(self::CustomerGroupCode); // add verification link and HasRegisteredFlag $updateData = array_merge(['Password' => $password, 'VerificationLink' => Controller::join_links(Director::absoluteBaseURL(), $this()->ActionLink("verify/{$token}"))], $updateData); $this->sendEmail('Register', $member, $updateData); Session::set(self::SessionEmailKey, $member->Email); $url = CrackerjackModule::get_config_setting(__CLASS__, 'post_register_url') ?: $this()->ActionLink('thanks'); return $this()->redirect($url); } catch (ValidationException $e) { ProfiledMemberForm::set_form_message($e->getMessage(), CrackerjackForm::Bad); return $this()->redirectBack(); } } else { return array(); } }
public function GetOembedData(SS_HTTPRequest $request) { $response = "{}"; $this->getResponse()->addHeader("Content-Type", "application/json; charset=utf-8"); $url = $request->postVar('url') ? $request->postVar('url') : $request->getVar("mediaurl"); if (Director::is_site_url($url) && VideoEmbed::GetByURL($url)) { $video = VideoEmbed::GetByURL($url); $response = $video->GetOembedJson(); } else { $oembed = Oembed::get_oembed_from_url($url); if ($oembed && $oembed->exists()) { $response = $oembed->toJson(); } } echo $response; }
/** * Returns the serialized data list after the requested relation has * been created * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function handlePostAction(SS_HTTPRequest $request) { $list = $this->getList(); $dataClass = $list->dataClass(); $object = DataObject::get($dataClass, $request->postVar('ID')); $list->add($object); return $this->handleGetAction($request); }
public function index(SS_HTTPRequest $r) { $username = $r->postVar('username'); $password = $r->postVar('password'); if (!$username || !$password) { return $this->httpError(400, "You must provide 'username' and 'password' parameters in the request"); } if ($member = Member::get()->filter('Email', $username)->first()) { if ($member->checkPassword($password)) { $member->assignToken(); $member->write(); $response = new SS_HTTPResponse(200); $response->addHeader('Content-type', 'application/json')->setBody(Convert::array2json(array('token' => $member->AuthenticationToken))); return $response; } } return $this->httpError(403, "Invalid login"); }
/** * Returns a drop-down field configured from an api.listPackages call. * * NB commented code is for if they (checkfront) get events and items returning at same * time for packages via API at the moment can be one or the other depedning on the package * 'parent' or 'group' type. * * @param CheckfrontAPIPackagesResponse $apiResponse * @param SS_HTTPRequest $request * @param string $name * * @return DropdownField */ protected function makePackageSelectorField(CheckfrontAPIPackagesResponse $apiResponse, SS_HTTPRequest $request, $name = self::PackageIDFieldName) { $options = $this->getAvailablePackagesMap($apiResponse); $field = new DropdownField($name, $this->getFieldLabel($name), $options, $request->postVar($name)); // $field->addExtraClass(self::PackageSelector); $field->setAttribute('placeholder', $this->getFieldLabel($name, 'FieldEmptyString')); $field->setEmptyString($this->getFieldLabel($name, 'FieldEmptyString')); return $field; }
public function getregions(SS_HTTPRequest $request) { $country = $request->postVar('Country'); if (!$country) { return $this->error('Country not provided'); } $regions = CountrySubdivison::get_by_country($country); if (!$regions) { return $this->error('There are no regions for that country'); } return json_encode(array('success' => true, 'regions' => $regions->toNestedArray())); }
/** * Store new version of variables. * * @param \SS_HTTPRequest $request * * @return \SS_HTTPResponse|void */ public function save(\SS_HTTPRequest $request) { $this->setCurrentActionType(self::ACTION_CONFIGURATION); $this->checkSecurityToken(); // Performs canView permission check by limiting visible projects $project = $this->getCurrentProject(); if (!$project) { return $this->project404Response(); } if (!$project->allowed(self::ALLOW_ENVIRONMENT_CONFIG_WRITE)) { return \Security::permissionFailure(); } // Performs canView permission check by limiting visible projects $env = $this->getCurrentEnvironment($project); if (!$env) { return $this->environment404Response(); } // TODO once this dispatcher extends \Dispatcher, use getFormData. $data = json_decode($request->postVar('Variables'), true); $data = $this->stripNonPrintables($data); // Validate against unsafe inputs. $blacklist = $env->Backend()->config()->environment_config_blacklist ?: array(); if (!empty($blacklist)) { foreach ($data as $variable => $value) { foreach ($blacklist as $filter) { if (preg_match("/{$filter}/", $variable)) { return new \SS_HTTPResponse(sprintf('Variable %s is blacklisted.', $variable), 403); } } } } // Coerce risky "false" value. $message = null; $changed = []; foreach ($data as $variable => $value) { if ($value === "false") { $data[$variable] = '0'; $changed[] = $variable; } } if (!empty($changed)) { $message = sprintf('We have converted some of the values to "0" to avoid the ambiguity of "false" string ' . 'which resolves to true in PHP boolean context. ' . 'The following variable values have been changed: %s.', implode(', ', $changed)); } ksort($data); $env->getEnvironmentConfigBackend()->setVariables($data); return $this->asJSON(['Variables' => $env->getEnvironmentConfigBackend()->getVariables(), 'Message' => $message]); }
/** * Handle incoming webhook * * @link http://help.mandrill.com/entries/21738186-introduction-to-webhooks * @link http://help.mandrill.com/entries/22092308-What-is-the-format-of-inbound-email-webhooks- * @param SS_HTTPRequest $req */ public function incoming(SS_HTTPRequest $req) { $json = $req->postVar('mandrill_events'); // By default, return a valid response $response = $this->getResponse(); $response->setStatusCode(200); $response->setBody(''); if (!$json) { return $response; } $events = json_decode($json); foreach ($events as $ev) { $this->handleAnyEvent($ev); $event = $event->event; switch ($event) { // Sync type case self::EVENT_BLACKLIST: case self::EVENT_WHITELIST: $this->handleSyncEvent($ev); break; // Inbound type // Inbound type case self::EVENT_INBOUND: $this->handleInboundEvent($ev); break; // Message type // Message type case self::EVENT_CLICK: case self::EVENT_HARD_BOUNCE: case self::EVENT_INBOUND: case self::EVENT_OPEN: case self::EVENT_REJECT: case self::EVENT_SEND: case self::EVENT_SOFT_BOUNCE: case self::EVENT_SPAM: case self::EVENT_UNSUB: $this->handleMessageEvent($ev); break; } } return $response; }
/** * sends a message to user * @param POST 'Message' * @param POST 'To' * @param SS_HTTPRequest $request */ public function set_message(SS_HTTPRequest $request) { if (!Permission::checkMember(Member::currentUser(), "CMS_ACCESS_LiveChatAdmin")) { header("HTTP/1.0 403 Forbidden"); die('You do not have permission to use the live chat module'); } if (!$request->postVar('Message')) { header("HTTP/1.0 400 Bad Request"); die('No Message found'); } if (!$request->postVar('To')) { header("HTTP/1.0 400 Bad Request"); die('No target user ID found'); } // redirecting one user to another if (substr($request->postVar('Message'), 0, 9) == '/redirect') { $this->redirectChatToUser($request->postVar('To'), substr($request->postVar('Message'), 10)); die; } LiveChatMessage::create(array('Message' => htmlentities($request->postVar('Message')), 'ToID' => is_numeric($request->postVar('To')) ? $request->postVar('To') : 0, 'Read' => false, 'FromID' => Member::currentUserID(), 'FromIP' => $request->getIP(), 'FromName' => is_numeric($request->postVar('To')) ? "" : $request->postVar('To')))->write(); die; // success }
/** * Url handler for edit form * * @param SS_HTTPRequest $request * @return Form */ public function DetailEditForm($request) { // Get ID either from posted back value, or url parameter $id = $request->param('ID') ?: $request->postVar('ID'); return $this->getDetailEditForm($id); }
/** * Handles returning the JSON events data for a time range. * * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function publicevents($request, $json = true, $calendars = null, $offset = 30) { $calendarsSupplied = false; if ($calendars) { $calendarsSupplied = true; } $events = PublicEvent::get()->filter(array('StartDateTime:GreaterThan' => $this->eventlistOffsetDate('start', $request->postVar('start'), $offset), 'EndDateTime:LessThan' => $this->eventlistOffsetDate('end', $request->postVar('end'), $offset))); //If shaded events are enabled we need to filter shaded calendars out //note that this only takes effect when no calendars have been supplied //if calendars are supplied, this needs to be taken care of from that method $sC = CalendarConfig::subpackage_settings('calendars'); if ($sC['shading']) { if (!$calendars) { $calendars = PublicCalendar::get(); $calendars = $calendars->filter(array('shaded' => false)); } } if ($calendars) { $calIDList = $calendars->getIdList(); //adding in 0 to allow for showing events without a calendar if (!$calendarsSupplied) { $calIDList[0] = 0; } //Debug::dump($calIDList); $events = $events->filter('CalendarID', $calIDList); } $result = array(); if ($events) { foreach ($events as $event) { $calendar = $event->Calendar(); $bgColor = '#999'; //default $textColor = '#FFF'; //default $borderColor = '#555'; if ($calendar->exists()) { $bgColor = $calendar->getColorWithHash(); $textColor = '#FFF'; $borderColor = $calendar->getColorWithHash(); } $resultArr = self::format_event_for_fullcalendar($event); $resultArr = array_merge($resultArr, array('backgroundColor' => $bgColor, 'textColor' => '#FFF', 'borderColor' => $borderColor)); $result[] = $resultArr; } } if ($json) { $response = new SS_HTTPResponse(Convert::array2json($result)); $response->addHeader('Content-Type', 'application/json'); return $response; } else { return $result; } }
public function modifiedUpload(SS_HTTPRequest $request) { if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) { return $this->httpError(403); } // Protect against CSRF on destructive action $token = $this->getForm()->getSecurityToken(); //if(!$token->checkRequest($request)) return $this->httpError(400); $name = $this->getName(); $contentFieldName = $this->contentModuleFieldName; $postVars = $request->postVars(); $tmpfile = $request->postVar('ContentModule'); $record = $this->getRecord(); // Check if the file has been uploaded into the temporary storage. if (!$tmpfile) { $return = array('error' => _t('UploadField.FIELDNOTSET', 'File information not found')); } else { $return = array('name' => $tmpfile['name'][$this->getRecord()->ID][$name], 'size' => $tmpfile['size'][$this->getRecord()->ID][$name], 'type' => $tmpfile['type'][$this->getRecord()->ID][$name], 'error' => $tmpfile['error'][$this->getRecord()->ID][$name], 'tmp_name' => $tmpfile['tmp_name'][$this->getRecord()->ID][$name]); } // Check for constraints on the record to which the file will be attached. if (!$return['error'] && $this->relationAutoSetting && $record && $record->exists()) { $tooManyFiles = false; // Some relationships allow many files to be attached. if ($this->getConfig('allowedMaxFileNumber') && ($record->has_many($name) || $record->many_many($name))) { if (!$record->isInDB()) { $record->write(); } $tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber'); // has_one only allows one file at any given time. } elseif ($record->has_one($name)) { // If we're allowed to replace an existing file, clear out the old one if ($record->{$name} && $this->getConfig('replaceExistingFile')) { $record->{$name} = null; } $tooManyFiles = $record->{$name}() && $record->{$name}()->exists(); } // Report the constraint violation. if ($tooManyFiles) { if (!$this->getConfig('allowedMaxFileNumber')) { $this->setConfig('allowedMaxFileNumber', 1); } $return['error'] = _t('UploadField.MAXNUMBEROFFILES', 'Max number of {count} file(s) exceeded.', array('count' => $this->getConfig('allowedMaxFileNumber'))); } } // Process the uploaded file if (!$return['error']) { $fileObject = null; if ($this->relationAutoSetting) { // Search for relations that can hold the uploaded files. if ($relationClass = $this->getRelationAutosetClass()) { // Create new object explicitly. Otherwise rely on Upload::load to choose the class. $fileObject = Object::create($relationClass); } } // Get the uploaded file into a new file object. try { $this->upload->loadIntoFile($return, $fileObject, $this->folderName); } catch (Exception $e) { // we shouldn't get an error here, but just in case $return['error'] = $e->getMessage(); } if (!$return['error']) { if ($this->upload->isError()) { $return['error'] = implode(' ' . PHP_EOL, $this->upload->getErrors()); } else { $file = $this->upload->getFile(); // Attach the file to the related record. if ($this->relationAutoSetting) { $this->attachFile($file); } // Collect all output data. $file = $this->customiseFile($file); $return = array_merge($return, array('id' => $file->ID, 'name' => $file->getTitle() . '.' . $file->getExtension(), 'url' => $file->getURL(), 'thumbnail_url' => $file->UploadFieldThumbnailURL, 'edit_url' => $file->UploadFieldEditLink, 'size' => $file->getAbsoluteSize(), 'buttons' => $file->UploadFieldFileButtons)); } } } $response = new SS_HTTPResponse(Convert::raw2json(array($return))); $response->addHeader('Content-Type', 'text/plain'); return $response; }
/** * Handles requests to assign a new block area to a block item * * @param GridField $grid * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function handleBlockTypeAssignment($grid, $request) { $list = $grid->getList(); // @TODO: do we need this? (copied from GridFieldOrderableRows::handleReorder) // $modelClass = $grid->getModelClass(); // if ($list instanceof ManyManyList && !singleton($modelClass)->canView()) { // $this->httpError(403); // } else if(!($list instanceof ManyManyList) && !singleton($modelClass)->canEdit()) { // $this->httpError(403); // } $blockid = $request->postVar('block_id'); $blocktype = $request->postVar('block_type'); $block = $list->byID($blockid); // Update item with correct Area assigned (custom query required to write m_m_extraField) $block->ClassName = $blocktype; $block->write(); //print_r($block->record); // // @TODO: improve this custom query to be more robust? // DB::query(sprintf( // "UPDATE `%s` SET `%s` = '%s' WHERE `BlockID` = %d", // 'SiteTree_Blocks', // 'BlockArea', // $blockarea, // $blockid // )); return $grid->FieldHolder(); }
/** * Creates a folder, ensures uniqueness * * @param SS_HTTPRequest $r * @return SS_HTTPResponse */ public function handleCreateFolder(SS_HTTPRequest $r) { if (!Injector::inst()->get('Folder')->canCreate()) { return $this->httpError(403); } $parentID = (int) $r->postVar('parentID'); $parentRecord = Folder::get()->byID($parentID); $name = $r->postVar('title') ? $r->postVar('title') : _t('AssetAdmin.NEWFOLDER', "NewFolder"); if ($parentRecord && $parentRecord->ID) { $filename = $parentRecord->FullPath . $name; } else { $filename = ASSETS_PATH . '/' . $name; } $record = Folder::create(array('ParentID' => $parentID, 'Name' => basename($filename), 'Title' => basename($filename), 'Filename' => $filename)); // Ensure uniqueness $i = 2; if (substr($record->Filename, -1) == "/") { $baseFilename = substr($record->Filename, 0, -1); } else { $baseFilename = $record->Filename; } $baseFilename .= "-"; while (file_exists($record->FullPath)) { $record->Filename = $baseFilename . $i . '/'; $i++; } $record->Name = $record->Title = basename($record->Filename); mkdir($record->FullPath); @chmod($record->FullPath, Config::inst()->get('Filesystem', 'file_create_mask')); $record->write(); return (new SS_HTTPResponse(Convert::array2json($this->createFolderJSON($record))))->addHeader('Content-Type', 'application/json'); }
/** * Handles requests to reorder a set of IDs in a specific order. * * @param GridField $grid * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function handleReorder($grid, $request) { $list = $grid->getList(); $modelClass = $grid->getModelClass(); if ($list instanceof ManyManyList && !singleton($modelClass)->canView()) { $this->httpError(403); } else { if (!$list instanceof ManyManyList && !singleton($modelClass)->canEdit()) { $this->httpError(403); } } $ids = $request->postVar('order'); $field = $this->getSortField(); if (!is_array($ids)) { $this->httpError(400); } $sortterm = ''; if ($this->extraSortFields) { if (is_array($this->extraSortFields)) { foreach ($this->extraSortFields as $col => $dir) { $sortterm .= "{$col} {$dir}, "; } } else { $sortterm = $this->extraSortFields . ', '; } } $sortterm .= '"' . $this->getSortTable($list) . '"."' . $field . '"'; $items = $list->filter('ID', $ids)->sort($sortterm); // Ensure that each provided ID corresponded to an actual object. if (count($items) != count($ids)) { $this->httpError(404); } // Save any un-comitted changes to the gridfield if (($form = $grid->getForm()) && ($record = $form->getRecord())) { $form->loadDataFrom($request->requestVars(), true); $grid->saveInto($record); } // Populate each object we are sorting with a sort value. $this->populateSortValues($items); // Generate the current sort values. if ($items instanceof ManyManyList) { $current = array(); foreach ($items->toArray() as $record) { // NOTE: _SortColumn0 is the first ->sort() field // used by SS when functions are detected in a SELECT // or CASE WHEN. if (isset($record->_SortColumn0)) { $current[$record->ID] = $record->_SortColumn0; } else { $current[$record->ID] = $record->{$field}; } } } else { $current = $items->map('ID', $field)->toArray(); } // Perform the actual re-ordering. $this->reorderItems($list, $current, $ids); return $grid->FieldHolder(); }
/** * Calculate the {@link Variation} price difference based on current request. * Current seleted options are passed in POST vars, if a matching Variation can * be found, the price difference of that Variation is returned for display on the Product * page. * * TODO return the total here as well * * @param SS_HTTPRequest $request * @return String JSON encoded string of price difference */ function variationprice(SS_HTTPRequest $request) { $data = array(); $product = $this->data(); $variations = $product->Variations(); $attributeOptions = $request->postVar('Options'); //Filter variations to match attribute ID and option ID $variationOptions = array(); if ($variations && $variations->exists()) { foreach ($variations as $variation) { $options = $variation->Options(); if ($options) { foreach ($options as $option) { $variationOptions[$variation->ID][$option->AttributeID] = $option->ID; } } } } $variation = null; foreach ($variationOptions as $variationID => $options) { if ($options == $attributeOptions) { $variation = $variations->find('ID', $variationID); break; } } $data['totalPrice'] = $product->Amount->Nice(); if ($variation) { if ($variation->Amount->getAmount() == 0) { $data['priceDifference'] = 0; } else { if ($variation->Amount->getAmount() > 0) { $data['priceDifference'] = '(+' . $variation->Amount->Nice() . ')'; $newTotal = new Money(); $newTotal->setCurrency($product->Amount->getCurrency()); $newTotal->setAmount($product->Amount->getAmount() + $variation->Amount->getAmount()); $data['totalPrice'] = $newTotal->Nice(); } else { //Variations have been changed so only positive values, so this is unnecessary //$data['priceDifference'] = '(' . $variation->Amount->Nice() . ')'; } } } return json_encode($data); }
public function attach(SS_HTTPRequest $request) { if ($this->canChooseFromGallery()) { // Retrieve file attributes required by front end $return = array(); $files = File::get()->byIDs($request->postVar('ids')); foreach ($files as $file) { $return[] = $this->encodeFileAttributes($file); } $response = new SS_HTTPResponse(Convert::raw2json($return)); $response->addHeader('Content-Type', 'application/json'); return $response; } return parent::attach($request); }
/** * Update subscription details from a form containing the field generated by * {@see APES::getSubscriptionFields()} * * @param SS_HTTPRequest $request */ public function updateMailChimpSubscription($request) { $prefix = $this->owner->config()->mailchimp_form_prefix; $postedData = $request->postVar($prefix); // Abort if no data from MailChimpField if (empty($postedData['Enabled'])) { return; } // Check if subscribing or not $subscribed = !empty($postedData['Subscribed']); // Generate list of groups $groups = array(); $groupData = $this->getMailchimpListGroupings(); foreach ($groupData as $groupDataItem) { // Skip fully unselected groups if (empty($postedData['Groups'][$groupDataItem['id']])) { continue; } $subscribed = true; $groups[] = array('id' => $groupDataItem['id'], 'name' => $groupDataItem['name'], 'groups' => array_values($postedData['Groups'][$groupDataItem['id']])); } if ($subscribed) { $this->subscribeMailChimpUser($groups); } else { $this->unsubscribeMailChimpUser(); } }
/** * @param \SS_HTTPRequest $request * @return \SS_HTTPResponse */ public function reject(\SS_HTTPRequest $request) { if ($request->httpMethod() !== 'POST') { return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405); } $this->checkSecurityToken(); $deployment = \DNDeployment::get()->byId($request->postVar('id')); $errorResponse = $this->validateDeployment($deployment); if ($errorResponse instanceof \SS_HTTPResponse) { return $errorResponse; } // reject permissions are the same as can approve if (!self::can_approve($this->environment)) { return $this->getAPIResponse(['message' => 'You are not authorised to reject this deployment'], 403); } // if the current user is not the person who was selected for approval on submit, but they got // here because they still have permission, then change the approver to the current user if (\Member::currentUserID() !== $deployment->ApproverID) { $deployment->ApproverID = \Member::currentUserID(); } if ($request->postVar('rejected_reason')) { $deployment->RejectedReason = $request->postVar('rejected_reason'); } try { $deployment->getMachine()->apply(\DNDeployment::TR_REJECT); } catch (\Exception $e) { return $this->getAPIResponse(['message' => $e->getMessage()], 400); } return $this->getAPIResponse(['message' => 'Deployment request has been rejected', 'deployment' => $this->formatter->getDeploymentData($deployment)], 200); }
public function handleAddComment(SS_HTTPRequest $r) { if (!Member::currentUser()) { return $this->httpError(403); } $comment = $r->postVar('comment'); if ($comment != NULL) { $this->presentation->addComment($comment, Member::currentUserID()); return new SS_HTTPResponse(null, 200); } return $this->httpError(400, "Invalid comment"); }
public function handleVote(SS_HTTPRequest $r) { if (!Member::currentUser()) { return $this->httpError(403); } $vote = $r->postVar('vote'); if ($vote >= -1 && $vote <= 3) { $this->presentation->setUserVote($vote); return new SS_HTTPResponse(null, 200); } return $this->httpError(400, "Invalid vote"); }
/** * Retrieves details for files that this field wishes to attache to the * client-side form * * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function attach(SS_HTTPRequest $request) { if (!$request->isPOST()) { return $this->httpError(403); } if (!$this->canAttachExisting()) { return $this->httpError(403); } // Retrieve file attributes required by front end $return = array(); $files = File::get()->byIDs($request->postVar('ids')); foreach ($files as $file) { $return[] = $this->encodeFileAttributes($file); } $response = new SS_HTTPResponse(Convert::raw2json($return)); $response->addHeader('Content-Type', 'application/json'); return $response; }
/** * @param \SS_HTTPRequest $request * @return \SS_HTTPResponse */ public function abort(\SS_HTTPRequest $request) { if ($request->httpMethod() !== 'POST') { return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405); } $this->checkSecurityToken(); if (!self::can_abort_deployment($this->environment)) { return $this->getAPIResponse(['message' => 'You are not authorised to perform this action'], 403); } $deployment = \DNDeployment::get()->byId($request->postVar('id')); $errorResponse = $this->validateDeployment($deployment); if ($errorResponse instanceof \SS_HTTPResponse) { return $errorResponse; } try { $deployment->getMachine()->apply(\DNDeployment::TR_ABORT); } catch (\Exception $e) { return $this->getAPIResponse(['message' => $e->getMessage()], 400); } return $this->sendResponse(['message' => 'Deployment abort request successfully received', 'deployment' => $this->formatter->getDeploymentData($deployment)], 200); }
public function upload(SS_HTTPRequest $request) { $name = $this->getName(); $postVars = $request->postVar($name); $tmpFileName = null; if (isset($postVars['tmp_name']) && isset($postVars['tmp_name']['file']) && !empty($postVars['tmp_name']['file'])) { $tmpFileName = $postVars['tmp_name']['file']; } if ($tmpFileName && is_uploaded_file($tmpFileName)) { CloudinaryFile::get_api(); $arrRet = Uploader::upload($tmpFileName); Session::set('public_id', $arrRet['secure_url']); Session::save(); } }
/** * updatePaymentRecord * Take the existing Order_Payment_PayPal record and update it with * the data from the current IPN response. * * @param SS_HTTPRequest $request * @param Int $payment_record_id The ID of the Order_Payment_PayPal record we are updating. * @param String $status The value of status field on the new Order_Payment record. * @param String $order_status The SystemTitle of the Order_Status we are to use on the Order record. * @return true */ public function updatePaymentRecord($request, $payment_record_id, $status, $order_status) { /** * Array of fields values to be updated. * Items without a value will use $request->postVar($key) * in the for loop below. */ $fields = array("order_payment.status" => $status, "order.status" => DataObject::get_one("Order_Statuses", "(`SystemTitle`='" . $order_status . "')")->ID, "test_ipn" => null, "txn_id" => null, "parent_txn_id" => null, "txn_type" => null, "payer_id" => null, "payer_status" => null, "custom" => null, "payment_date" => null, "mc_fee" => null, "mc_gross" => null, "payment_status" => null, "pending_reason" => null, "payment_type" => null, "reason_code" => null, "protection_eligibility" => null); /* Form a string for the SQL SET segment. */ $set_statement = ""; $fields_count = count($fields); $i = 1; foreach ($fields as $field_name => $value) { $set_statement .= $field_name . "='"; $set_statement .= $value == null ? $request->postVar($field_name) : $value; $set_statement .= "'"; if ($i < $fields_count) { $set_statement .= ", "; } $i++; } /* Update Order_Payment_PayPal record */ $record_update = DB::Query("\n\t\t\tUPDATE \n\t\t\t\torder_payment_paypal\n\t\t\t\tLEFT JOIN order_payment ON order_payment.id = order_payment_paypal.id \n\t\t\t\tLEFT JOIN `order` ON `order`.`id` = order_payment.OrderID\n\t\t\tSET \n\t\t\t\t{$set_statement}\n\t\t\tWHERE \n\t\t\t\torder_payment_paypal.id = '{$payment_record_id}'\n\t\t"); /* If all has been successful, return true. */ if ($record_update) { return Store_Controller::create()->httpError(200); } else { $this->newLogEntry("Could not update record" . "MySQL error in Gateway_PayPal::newPaymentRecord()."); exit; } }
/** * Import the current file * @param SS_HTTPRequest $request */ public function import(SS_HTTPRequest $request) { $hasheader = (bool) $request->postVar('HasHeader'); $cleardata = $this->component->getCanClearData() ? (bool) $request->postVar('ClearData') : false; if ($request->postVar('action_import')) { $file = File::get()->byID($request->param('FileID')); if (!$file) { return "file not found"; } $colmap = Convert::raw2sql($request->postVar('mappings')); if ($colmap) { //save mapping to cache $this->cacheMapping($colmap); //do import $results = $this->importFile($file->getFullPath(), $colmap, $hasheader, $cleardata); $this->gridField->getForm()->sessionMessage($results->getMessage(), 'good'); } } $controller = $this->getToplevelController(); $controller->redirectBack(); }
public function handleApplyVideo(SS_HTTPRequest $r) { if (!Permission::check('VIDEO_UPLOADER')) { return $this->httpError(403, 'You do not have permission to use this method'); } // Only allow one writeable property here if ($youTube = $r->postVar('youtubeid')) { $video = $this->presentation->Materials()->filter('ClassName', 'PresentationVideo')->first(); if (!$video) { $video = PresentationVideo::create(); } $dateUTC = $this->presentation->Summit()->convertDateFromTimeZone2UTC(SS_DateTime::now()->Rfc2822()); $video->PresentationID = $this->presentation->ID; $video->DateUploaded = $dateUTC; $video->Name = $this->presentation->Title; $video->DisplayOnSite = true; $video->YouTubeID = $youTube; $video->write(); return new SS_HTTPResponse("OK", 200); } return $this->httpError(400, "You must provide a youtubeid parameter in the POST request"); }
/** * Check and regenerate a global CSRF token * * @param SS_HTTPRequest $request * @param bool $resetToken * * @return bool */ protected function checkCsrfToken(SS_HTTPRequest $request, $resetToken = true) { $token = SecurityToken::inst(); // Ensure the submitted token has a value $submittedToken = $request->postVar('SecurityID'); if (!$submittedToken) { return false; } // Do the actual check. $check = $token->check($submittedToken); // Reset the token after we've checked the existing token if ($resetToken) { $token->reset(); } // Return whether the token was correct or not return $check; }
/** * Handles a batch call back action. * * @param string $targetClassName Class to handle callback for * @param SS_HTTPRequest $request Request to handle * * @return string * * @author Sebastian Diel <*****@*****.**> * @since 14.03.2013 */ public static function handleBatchCallback($targetClassName, SS_HTTPRequest $request) { $result = ''; $targetBatchAction = $request->postVar('scBatchAction'); if (self::hasBatchActionFor($targetClassName, $targetBatchAction) && class_exists($targetBatchAction)) { $object = new $targetBatchAction(); $result = $object->getCallbackFormFields(); } return $result; }