/** * Default action handler for this page * * @param SS_HTTPRequest $request * @return Object AfterPurchasePage */ public function afterPurchase(SS_HTTPRequest $request) { if ($request->isGET()) { if ($this->validateClickBankRequest) { $cbreceipt = $request->getVar('cbreceipt'); $cbpop = $request->getVar('cbpop'); $name = $request->getVar('cname'); $email = $request->getVar('cemail'); if (!empty($cbreceipt) && !empty($cbpop)) { if (ClickBankManager::validate_afterpurchase_request($request->getVars())) { $member = DataObject::get_one('Member', "Email = '{$email}'"); // make the member status to logged-in if ($member && $this->loginAfterClickBankRequestIsValid) { $member->logIn(); } // few handy replacement texts $content = $this->Content; $content = str_replace('$CBReceipt', $cbreceipt, $content); $content = str_replace('$CBName', $name, $content); $data = array('Title' => $this->Title, 'Content' => $content); return $this->customise($data)->renderWith(array('AfterPurchasePage' => 'Page')); } } } else { $data = array('Title' => $this->Title, 'Content' => $this->Content); return $this->customise($data)->renderWith(array('AfterPurchasePage' => 'Page')); } } return $this->redirect('/server-error'); }
/** * Check that the payment was successful using "Process Response" API (http://www.paymentexpress.com/Technical_Resources/Ecommerce_Hosted/PxPay.aspx). * * @param SS_HTTPRequest $request Request from the gateway - transaction response * @return PaymentGateway_Result */ public function check($request) { $data = $request->getVars(); $url = $request->getVar('url'); $result = $request->getVar('result'); $userID = $request->getVar('userid'); //Construct the request to check the payment status $request = new PxPayLookupRequest(); $request->setResponse($result); //Get encrypted URL from DPS to redirect the user to $request_string = $this->makeCheckRequest($request, $data); //Obtain output XML $response = new MifMessage($request_string); //Parse output XML $success = $response->get_element_text('Success'); if ($success && is_numeric($success) && $success > 0) { return new PaymentGateway_Success(); } else { if (is_numeric($success) && $success == 0) { return new PaymentGateway_Failure(); } else { return new PaymentGateway_Incomplete(); } } }
public function index(SS_HTTPRequest $r) { $p = SchedPresentation::get()->filter(array('DisplayOnSite' => true)); $k = $r->getVar('Keywords'); $cat = $r->getVar('Category'); $speaker = $r->getVar('Speaker'); $summit = $r->getVar('Summit'); $tag = $r->getVar('Tag'); if (!empty($k)) { $p = $p->filterAny(array('Title:PartialMatch' => $k, 'Description:PartialMatch' => $k, 'Tags.Title:ExactMatch' => $k)); } if (!empty($cat)) { $p = $p->filter(array('CategoryID' => $cat)); } if (!empty($speaker)) { $p = $p->filter(array('PresentationSpeakers.ID' => $speaker)); } if (!empty($summit)) { $p = $p->filter(array('SummmitID' => $summit)); } if (!empty($tag)) { $p = $p->filter(array('Tags.Title' => $tag)); } return array('Results' => new PaginatedList($p, $this->request)); }
/** * OAuth callback handler. * * @param SS_HTTPRequest $request */ public function OAuth($request) { $code = $request->getVar('code'); $state = $request->getVar('state'); if (!$code || !$state) { return Controller::curr()->redirect($this->Link()); } $client = InstagramAccount::getNewInstagramClient(); $form = $this->getEditForm(); try { $token = $client->getAccessToken($code); $instagramAccountID = $this->getInstagramAccountIDFromSession($state); // Find the matching InstagramAccount. if (!$instagramAccountID || !($instagramAccount = InstagramAccount::get()->byId($instagramAccountID))) { return $this->handleOAuthError($form); } try { $instagramAccount->updateAccessToken(Convert::raw2json($token), $state); $instagramAccount->write(); $form->sessionMessage(_t('Instagram.MessageOAuthSuccess', 'Successfully authorised your account.'), 'good'); return Controller::curr()->redirect($this->Link()); } catch (Exception $e) { return $this->handleOAuthError($form, _t('Instagram.MessageOAuthErrorUserConflict', 'Unable to authorise account. Make sure you are logged out of Instagram and ' . 'your username is spelled correctly.')); } } catch (InstagramIdentityProviderException $e) { return $this->handleOAuthError($form); } }
/** * Request nodes from the server * * @param SS_HTTPRequest $request * @return JSONString */ public function childnodes($request) { $data = array(); $rootObjectType = 'SiteTree'; if ($request->param('ID')) { $rootObjectType = $request->param('ID'); } if ($request->getVar('search')) { return $this->performSearch($request->getVar('search'), $rootObjectType); } $parentId = $request->getVar('id'); if (!$parentId) { $parentId = $rootObjectType . '-0'; } $selectable = null; if ($request->param('OtherID')) { $selectable = explode(',', $request->param('OtherID')); } list($type, $id) = explode('-', $parentId); if (!$type || $id < 0) { $data = array(0 => array('data' => 'An error has occurred')); } else { $children = null; if ($id == 0) { $children = DataObject::get($rootObjectType, 'ParentID = 0'); } else { $object = DataObject::get_by_id($type, $id); $children = $this->childrenOfNode($object); } $data = array(); if ($children && count($children)) { foreach ($children as $child) { if ($child->ID < 0) { continue; } $haskids = $child->numChildren() > 0; $nodeData = array('title' => isset($child->MenuTitle) ? $child->MenuTitle : $child->Title); if ($selectable && !in_array($child->ClassName, $selectable)) { $nodeData['clickable'] = false; } $thumbs = null; if ($child->ClassName == 'Image') { $thumbs = $this->generateThumbnails($child); $nodeData['icon'] = $thumbs['x16']; } else { if (!$haskids) { $nodeData['icon'] = 'frontend-editing/images/page.png'; } } $nodeEntry = array('attributes' => array('id' => $child->ClassName . '-' . $child->ID, 'title' => Convert::raw2att($nodeData['title']), 'link' => $child->RelativeLink()), 'data' => $nodeData, 'state' => $haskids ? 'closed' : 'open'); if ($thumbs) { $nodeEntry['thumbs'] = $thumbs; } $data[] = $nodeEntry; } } } return Convert::raw2json($data); }
public function tree(SS_HTTPRequest $request) { $oldSubsiteID = Session::get('SubsiteID'); if ($request->getVar($this->name . '_SubsiteID')) { $this->subsiteID = $request->getVar($this->name . '_SubsiteID'); } Session::set('SubsiteID', $this->subsiteID); $results = parent::tree($request); Session::set('SubsiteID', $oldSubsiteID); return $results; }
public function format(SS_HTTPRequest $request) { $rawNumber = $request->getVar('number'); $country = $request->getVar('country'); $format = $request->getVar('format'); try { return LibPhoneNumberField::formatPhoneNumber($rawNumber, $country, $format); } catch (\libphonenumber\NumberParseException $e) { SS_Log::log($e->getMessage(), SS_Log::DEBUG); return $this->httpError(400, $e->getMessage()); } }
public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model) { if ($request->getVar('clear') && Member::currentUserID() && Permission::check('ADMIN')) { $key = trim($request->getVar('url'), '/'); $key = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . '/' . $key; $item = $this->dynamicCache->get($key); if ($item) { $response->addHeader('X-SilverStripe-Cache', 'deleted ' . $key); $this->dynamicCache->delete($key); } } }
/** * @param SS_HTTPRequest $request * @return bool */ public function run($request) { /* @var $permissionChecker AnnotatePermissionChecker */ $permissionChecker = Injector::inst()->get('AnnotatePermissionChecker'); if (!$permissionChecker->environmentIsAllowed()) { return false; } /* @var $annotator DataObjectAnnotator */ $annotator = DataObjectAnnotator::create(); $annotator->annotateObject($request->getVar('object')); $annotator->annotateModule($request->getVar('module')); return true; }
public function handleGetAllPresentations(SS_HTTPRequest $r) { $limit = $r->getVar('limit') ?: 50; if ($limit > 50) { $limit = 50; } $start = $r->getVar('page') ?: 0; $presentations = Member::currentUser() ? Member::currentUser()->getRandomisedPresentations() : Presentation::get()->filter(array('SummitEvent.SummitID' => Summit::get_active()->ID)); if ($r->getVar('category')) { $presentations = $presentations->filter('CategoryID', (int) $r->getVar('category')); } if ($r->getVar('keyword')) { $k = $r->getVar('keyword'); $presentations = $presentations->filterAny(array('Title:PartialMatch' => $k, 'Description:PartialMatch' => $k, 'Speakers.FirstName:PartialMatch' => $k, 'Speakers.LastName:PartialMatch' => $k)); } if ($r->getVar('voted') == "true") { $presentations = $presentations->leftJoin("PresentationVote", "PresentationVote.PresentationID = Presentation.ID")->where("IFNULL(PresentationVote.MemberID,0) = " . Member::currentUserID()); } if ($r->getVar('voted') == "false") { $presentations = $presentations->leftJoin("PresentationVote", "PresentationVote.PresentationID = Presentation.ID")->where("IFNULL(PresentationVote.MemberID,0) != " . Member::currentUserID()); } $count = $presentations->count(); $presentations = $presentations->limit($limit, $start * $limit); $data = array('results' => array(), 'has_more' => $count > $limit * ($start + 1), 'total' => $count, 'remaining' => $count - $limit * ($start + 1)); foreach ($presentations as $p) { $data['results'][] = array('id' => $p->ID, 'title' => $p->Title, 'user_vote' => $p->getUserVote() ? $p->getUserVote()->Vote : null); } return (new SS_HTTPResponse(Convert::array2json($data), 200))->addHeader('Content-Type', 'application/json'); }
/** * Determins if the given request is from a bot * * Google ranks sites with the same content on different URLs lower. * This makes the site deliver single pages to bots * * @link http://www.beautifulcoding.com/snippets/178/a-simple-php-bot-checker-are-you-human/ * @return boolean */ public static function isRequsetBot(\SS_HTTPRequest $request) { $bots = Config::inst()->get('AllInOnePage', 'Bots'); $result = $request->getVar("mockBot") == "true"; if (!$result) { foreach ($bots as $spider) { //If the spider text is found in the current user agent, then return true if (stripos($request->getHeader("User-Agent"), $spider) !== false) { $result = true; } } } // echo '<pre class="debug"> "$result"' . PHP_EOL . print_r($result ? "yes" : "no", true) . PHP_EOL . '</pre>'; return $result || $request->getVar("mockBot") == "true"; }
public function delete(SS_HTTPRequest $request) { $rid = $request->getVar('RID'); $record = TestObject::get()->filter(array('ID' => $rid))->first(); $record->delete(); return $this->customise(new ArrayData(array('Title' => 'Orient DB Demo', 'SubTitle' => "Deleted Record {$rid}", 'Content' => $content)))->renderWith(array('OrientController', 'AppController')); }
/** * * @param SS_HTTPRequest $request */ public function run($request) { increase_time_limit_to(); echo 'Pass ?refresh=1 to refresh your members<br/>'; echo '<hr/>'; $refresh = $request->getVar('refresh'); if ($refresh) { DB::alteration_message("Resetting all members location"); DB::query('UPDATE Member SET Latitude = 0, Longitude = 0'); } $Members = Member::get()->filter(array('Latitude' => 0)); foreach ($Members as $Member) { DB::alteration_message('Processing member #' . $Member->ID . ' - ' . $Member->getTitle()); if (!$Member->Latitude) { if ($Member->canBeGeolocalized()) { DB::alteration_message($Member->GeocodeText()); if (!$Member->CountryCode) { DB::alteration_message("Warning ! This member has no country code", "error"); } /* @var $res Geocoder\Model\Address */ $res = $Member->Geocode(); if ($res) { DB::alteration_message('Geocode success on ' . $res->getLatitude() . ',' . $res->getLongitude() . ' : ' . $res->getStreetNumber() . ', ' . $res->getStreetName() . ' ' . $res->getPostalCode() . ' ' . $res->getLocality() . ' ' . $res->getCountry(), 'created'); $Member->write(); } else { DB::alteration_message('Geocode error', 'error'); } } else { DB::alteration_message('Cannot be geolocalized', 'error'); } } else { DB::alteration_message('Already geolocalized', 'error'); } } }
/** * @param SS_HTTPRequest $request */ public function run($request) { /** ========================================= * @var Page $page ===========================================*/ if (class_exists('Page')) { if (Page::has_extension('TwitterCardMeta')) { // Should we overwrite? $overwrite = $request->getVar('overwrite') ? true : false; echo sprintf('Overwrite is %s', $overwrite ? 'enabled' : 'disabled') . $this->eol . $this->eol; $pages = Page::get(); foreach ($pages as $page) { $id = $page->ID; echo $this->hr; echo 'Updating page: ' . $page->Title . $this->eol; foreach ($this->fields_to_update as $fieldName) { $oldData = DB::query("SELECT {$fieldName} FROM Page WHERE ID = {$id}")->column($fieldName); $newData = DB::query("SELECT {$fieldName} FROM SiteTree WHERE ID = {$id}")->column($fieldName); if (!empty($oldData)) { // If new data has been saved and we don't want to overwrite, exit the loop if (!empty($newData) && $overwrite === false) { continue; } DB::query("UPDATE SiteTree SET {$fieldName} = '{$oldData[0]}' WHERE ID = {$id}"); } else { echo 'Field "' . $fieldName . '" empty.' . $this->eol; } } } } } }
public function doGetProperties(SS_HTTPRequest $request) { $range = $request->getVar('range'); $list = $this->PropertyList()->filter(array('Latitude:LessThan' => floatval($range[0]), 'Latitude:GreaterThan' => floatval($range[2]), 'Longitude:LessThan' => floatval($range[1]), 'Longitude:GreaterThan' => floatval($range[3]))); $json = JSONDataFormatter::create()->convertDataObjectSet($list); return $json; }
protected static function getDefault(SS_HTTPRequest $request, $var, $default) { if ($value = $request->getVar($var)) { return $value; } return $default; }
/** * Returns a JSON string of tags, for lazy loading. * * @param SS_HTTPRequest $request * * @return SS_HTTPResponse */ public function suggest(SS_HTTPRequest $request) { $members = $this->getMembers($request->getVar('term')); $response = new SS_HTTPResponse(); $response->addHeader('Content-Type', 'application/json'); $response->setBody(json_encode($members)); return $response; }
/** * Accepts a list of ids in form of comma separated string via GET parameter. If any of these payments is no longer * pending, this method returns true, false otherwise. * @param $gridField * @param \SS_HTTPRequest|null $request * @return bool */ public function handleCheckPaymentPending($gridField, \SS_HTTPRequest $request = null) { if (!$request) { return false; } $ids = preg_split('/[^\\d]+/', $request->getVar('ids')); return \Payment::get()->filter('ID', $ids)->exclude('Status', array('PendingVoid', 'PendingCapture', 'PendingRefund'))->count() > 0; }
public function index(SS_HTTPRequest $request) { $screenshots = ModuleScreenshot::get()->limit(20); if ($search = $request->getVar('Title')) { $screenshots = $screenshots->filter(array('Title:PartialMatch' => $search)); } return array('Results' => $screenshots); }
/** * @param SS_HTTPRequest $request * @return string */ public function run($request) { $target = urldecode($request->getVar('target')); if (!$target) { return "Please provide a target as GET param."; } $parsedData = WebsiteParser::parse($target); var_dump($parsedData); }
/** * Handles returning the JSON events data for a time range. * * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function eventsdata($request) { $start = $request->getVar('start'); $end = $request->getVar('end'); // for testing if (!$end) { $end = '2013-12-12'; } $events = $this->owner->data()->getEventList(sfDate::getInstance($start)->date(), sfDate::getInstance($end)->date(), null, null); $result = array(); if ($events) { foreach ($events as $event) { $result[] = array('id' => $event->ID, 'title' => $event->getTitle(), 'start' => strtotime("{$event->StartDate} {$event->StartTime}"), 'end' => strtotime("{$event->EndDate} {$event->EndTime}"), 'startTime' => $event->getFormattedStartTime(), 'endTime' => $event->getFormattedEndTime(), 'allDay' => (bool) $event->AllDay, 'url' => $event->Link()); } } $this->owner->getRequest()->addHeader('Content-Type', 'application/json'); return Convert::array2json($result); }
/** * Returns the limit, either given in request by `limit` or from the default settings in the controller. * * @param \SS_HTTPRequest $request * @return int the limit value */ public function limit($request) { $limit = (int) $request->getVar('limit'); if ($limit && is_int($limit) && $limit > 0) { return $limit; } else { return static::$default_limit; } }
/** * @param \SS_HTTPRequest $request * @throws \Exception */ public function run($request) { $ds = DIRECTORY_SEPARATOR; if ($request->getVar('module')) { $this->setModulePath(BASE_PATH . $ds . $request->getVar('module')); } if (!is_dir($this->modulePath)) { throw new \Exception("Invalid module path: {$this->modulePath}"); } $iterator = new \GlobIterator($this->modulePath . $ds . $this->sourceDir . $ds . '*.json'); foreach ($iterator as $item) { $translations = file_get_contents($item->getPathName()); $locale = preg_replace('/\\.json/', '', $item->getFilename()); $targetPath = $this->modulePath . $ds . $this->targetDir . $ds . $locale . '.js'; echo "Generating {$targetPath}\n"; file_put_contents($targetPath, str_replace(array('%TRANSLATIONS%', '%FILE%', '%LOCALE%'), array($translations, $this->sourceDir . $ds . $item->getFilename(), $locale), $this->getTemplate())); } }
public function getReport(SS_HTTPRequest $request) { if (!Director::is_ajax()) { return $this->forbiddenError(); } $template_id = (int) $request->param('SURVEY_TEMPLATE_ID'); $section_id = (int) $request->getVar('section_id'); $filters = json_decode($request->getVar('filters')); try { $survey_template = SurveyTemplate::get_by_id('SurveyTemplate', $template_id); if (is_null($survey_template)) { return $this->httpError(404); } $section = $survey_template->Report()->Sections()->filter('ID', $section_id)->first(); return $this->ok($section->mapSection($filters)); } catch (Exception $ex) { return $ex->getMessage(); } }
/** * Check if we should merge * * @param SS_HTTPRequest $request */ protected function getIsMerge($request) { $merge = $request->getVar('merge'); // Default to false if not given if (!isset($merge)) { Deprecation::notice("4.0", "merge will be enabled by default in 4.0. Please use merge=false if you do not want to merge."); return false; } // merge=0 or merge=false will disable merge return !in_array($merge, array('0', 'false')); }
/** * Action to render results for an autocomplete filter. * * @param SS_HTTPRequest $request * @return void */ function filter($request) { //$model = singleton($this->modelClass); $context = $this->dataObject->getDefaultSearchContext(); $value = $request->getVar('q'); $results = $context->getResults(array("Name" => $value)); header("Content-Type: text/plain"); foreach ($results as $result) { echo $result->Name . "\n"; } }
/** * Action: get info about product set to help you determine how to appropriately use /products * @param SS_HTTPRequest $request */ function getinfo($request) { $limit = $request->getVar('limit') ? $request->getVar('limit') : 1000; $products = $this->ProductList(); $productsItems = PaginatedList::create($products, $request)->setPageLength($limit)->setPaginationGetVar('start'); $count = $products->Count(); $sets = floor($count / $limit); $setcount = $sets; echo '<p>There are a total of <strong>' . $count . '</strong> products.</p>'; echo '<p>Google should be provided with <strong>' . $setcount . '</strong> different feeds, showing ' . $limit . ' per page.</strong>'; for ($i = 0; $i <= $sets; $i++) { $counter = $limit * $i; $link = Director::absoluteURL('/googlebase/products/?limit=' . $limit); if ($i > 0) { $link .= '&start=' . $counter; } echo '<p><a href="' . $link . '" target="_blank">' . $link . '</a></p>'; } die; }
public function index(SS_HTTPRequest $request) { $products = Product::get(); if ($search = $request->getVar('Keywords')) { $products = $products->filter(array('Title:PartialMatch' => $search)); } if ($minPrice = $request->getVar('MinPrice')) { $products = $products->filter(array('Price:GreaterThanOrEqual' => $minPrice)); } if ($maxPrice = $request->getVar('MaxPrice')) { $products = $products->filter(array('Price:LessThanOrEqual' => $maxPrice)); } $paginatedProducts = PaginatedList::create($products, $request)->setPageLength(6); $data = array('Results' => $paginatedProducts); /* if($request->isAjax()){ return $this->customise(array( 'Results' => $paginatedProducts ))->renderWith('ProductSearchResults'); } */ if ($request->isAjax()) { return $this->customise($data)->renderWith('ProductSearchResults'); } return $data; }
public function index(SS_HTTPRequest $request) { $properties = Property::get(); if ($search = $request->getVar('Keywords')) { $properties = $properties->filter(array('Title:PartialMatch' => $search)); } if ($arrival = $request->getVar('ArrivalDate')) { $arrivalStamp = strtotime($arrival); $nightAdder = '+' . $request->getVar('Nights') . ' days'; $startDate = date('Y-m-d', $arrivalStamp); $endDate = date('Y-m-d', strtotime($nightAdder, $arrivalStamp)); $properties = $properties->filter(array('AvailableStart:LessThanOrEqual' => $startDate, 'AvailableEnd:GreaterThanOrEqual' => $endDate)); } if ($bedrooms = $request->getVar('Bedrooms')) { $properties = $properties->filter(array('Bedrooms:GreaterThanOrEqual' => $bedrooms)); } if ($bathrooms = $request->getVar('Bathrooms')) { $properties = $properties->filter(array('Bathrooms:GreaterThanOrEqual' => $bathrooms)); } if ($minPrice = $request->getVar('MinPrice')) { $properties = $properties->filter(array('PricePerNight:GreaterThanOrEqual' => $minPrice)); } if ($maxPrice = $request->getVar('MaxPrice')) { $properties = $properties->filter(array('PricePerNight:LessThanOrEqual' => $maxPrice)); } $paginatedProperties = PaginatedList::create($properties, $request)->setPageLength(15)->setPaginationGetVar('s'); $data = array('Results' => $paginatedProperties); if ($request->isAjax()) { return $this->customise($data)->renderWith('PropertySearchResults'); } return $data; }
public function index(SS_HTTPRequest $request) { $properties = Property::get(); $filters = ArrayList::create(); if ($search = $request->getVar('Keywords')) { $filters->push(ArrayData::create(array('Label' => "Keywords: '{$search}'", 'RemoveLink' => HTTP::setGetVar('Keywords', null)))); $properties = $properties->filter(array('Title:PartialMatch' => $search)); } if ($arrival = $request->getVar('ArrivalDate')) { $arrivalStamp = strtotime($arrival); $nightAdder = '+' . $request->getVar('Nights') . ' days'; $startDate = date('Y-m-d', $arrivalStamp); $endDate = date('Y-m-d', strtotime($nightAdder, $arrivalStamp)); $properties = $properties->filter(array('AvailableStart:GreaterThanOrEqual' => $startDate, 'AvailableEnd:LessThanOrEqual' => $endDate)); } if ($bedrooms = $request->getVar('Bedrooms')) { $filters->push(ArrayData::create(array('Label' => "{$bedrooms} bedrooms", 'RemoveLink' => HTTP::setGetVar('Bedrooms', null)))); $properties = $properties->filter(array('Bedrooms:GreaterThanOrEqual' => $bedrooms)); } if ($bathrooms = $request->getVar('Bathrooms')) { $filters->push(ArrayData::create(array('Label' => "{$bathrooms} bathrooms", 'RemoveLink' => HTTP::setGetVar('Bathrooms', null)))); $properties = $properties->filter(array('Bathrooms:GreaterThanOrEqual' => $bathrooms)); } if ($minPrice = $request->getVar('MinPrice')) { $filters->push(ArrayData::create(array('Label' => "Min. \${$minPrice}", 'RemoveLink' => HTTP::setGetVar('MinPrice', null)))); $properties = $properties->filter(array('PricePerNight:GreaterThanOrEqual' => $minPrice)); } if ($maxPrice = $request->getVar('MaxPrice')) { $filters->push(ArrayData::create(array('Label' => "Max. \${$maxPrice}", 'RemoveLink' => HTTP::setGetVar('MaxPrice', null)))); $properties = $properties->filter(array('PricePerNight:LessThanOrEqual' => $maxPrice)); } $paginatedProperties = PaginatedList::create($properties, $request)->setPageLength(15)->setPaginationGetVar('s'); return array('Results' => $paginatedProperties, 'ActiveFilters' => $filters); }