/**
  * The default implementation of the controller
  * is to call the serializeList method on its model.
  * @param SS_HTTPRequest $request
  * @return string|JsonDataResponse|SS_HTTPResponse
  */
 public function getList(SS_HTTPRequest $request)
 {
     $record = $this->getDataRecord();
     if ($record->hasMethod('getSerializedList')) {
         return $record->getSerializedList($request->getVars())->toJson();
     }
 }
 public function getLocationsByDay(SS_HTTPRequest $request)
 {
     try {
         $query_string = $request->getVars();
         $summit_id = intval($request->param('SUMMIT_ID'));
         $day = strtolower(Convert::raw2sql($query_string['day']));
         $summit = $this->summit_repository->getById($summit_id);
         if (is_null($summit)) {
             throw new NotFoundEntityException('Summit', sprintf(' id %s', $summit_id));
         }
         if (!$summit->isDayBelongs($day)) {
             throw new EntityValidationException(sprintf('day %s does not belongs to summit id %s', $day, $summit_id));
         }
         $response = array('day' => $day, 'summit_id' => intval($summit_id), 'locations' => array());
         foreach ($summit->getTopVenues() as $venue) {
             $class_name = $venue->ClassName;
             if ($class_name != 'SummitVenue' && $class_name != 'SummitExternalLocation' && $class_name != 'SummitHotel') {
                 continue;
             }
             $count = $summit->getPublishedEventsCountByDateLocation($day, $venue);
             array_push($response['locations'], array('id' => intval($venue->ID), 'events_count' => intval($count)));
             if ($class_name == 'SummitVenue') {
                 foreach ($venue->Rooms() as $room) {
                     $count = $summit->getPublishedEventsCountByDateLocation($day, $room);
                     array_push($response['locations'], array('id' => intval($room->ID), 'events_count' => intval($count)));
                 }
             }
         }
         return $this->ok($response);
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->serverError();
     }
 }
 /**
  * @param	SS_HTTPRequest $request
  */
 public function run($request)
 {
     // Only allow execution from the command line (for simplicity).
     if (!Director::is_cli()) {
         echo "<p>Sorry, but this can only be run from the command line.</p>";
         return;
     }
     try {
         // Get and validate desired maintenance mode setting.
         $get = $request->getVars();
         if (empty($get["args"])) {
             throw new Exception("Please provide an argument (e.g. 'on' or 'off').", 1);
         }
         $arg = strtolower(current($get["args"]));
         if ($arg != "on" && $arg != "off") {
             throw new Exception("Invalid argument: '{$arg}' (expected 'on' or 'off')", 2);
         }
         // Get and write site configuration now.
         $config = SiteConfig::current_site_config();
         $previous = !empty($config->MaintenanceMode) ? "on" : "off";
         $config->MaintenanceMode = $arg == "on";
         $config->write();
         // Output status and exit.
         if ($arg != $previous) {
             $this->output("Maintenance mode is now '{$arg}'.");
         } else {
             $this->output("NOTE: Maintenance mode was already '{$arg}' (nothing has changed).");
         }
     } catch (Exception $e) {
         $this->output("ERROR: " . $e->getMessage());
         if ($e->getCode() <= 2) {
             $this->output("Usage:  sake dev/tasks/MaintenanceMode [on|off]");
         }
     }
 }
 /**
  * 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 getAttendees(SS_HTTPRequest $request)
 {
     try {
         $query_string = $request->getVars();
         $page = isset($query_string['page']) ? Convert::raw2sql($query_string['page']) : '';
         $page_size = isset($query_string['items']) ? Convert::raw2sql($query_string['items']) : '';
         $search_term = isset($query_string['term']) ? Convert::raw2sql($query_string['term']) : '';
         $summit_id = intval($request->param('SUMMIT_ID'));
         $summit = $this->summit_repository->getById($summit_id);
         if (is_null($summit)) {
             throw new NotFoundEntityException('Summit', sprintf(' id %s', $summit_id));
         }
         list($attendees, $count) = $this->summitattendee_repository->findAttendeesBySummit($search_term, $page, $page_size, $summit_id);
         $attendees_array = array();
         foreach ($attendees as $attendee) {
             $attendees_array[] = array('id' => $attendee->ID, 'member_id' => $attendee->MemberID, 'name' => $attendee->Member->FullName, 'email' => $attendee->Member->Email, 'eventbrite_id' => $attendee->getTicketIDs(), 'ticket_bought' => $attendee->getBoughtDate(), 'checked_in' => $attendee->SummitHallCheckedIn, 'link' => 'summit-admin/' . $summit_id . '/attendees/' . $attendee->ID, 'schedule' => $attendee->Schedule()->toNestedArray());
         }
         return $this->ok(array('attendees' => $attendees_array, 'count' => $count));
     } catch (NotFoundEntityException $ex2) {
         SS_Log::log($ex2->getMessage(), SS_Log::WARN);
         return $this->notFound($ex2->getMessage());
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->serverError();
     }
 }
 /**
  * All requests pass through here and are redirected depending on HTTP verb and params
  * 
  * @param  SS_HTTPRequest        $request    HTTP request
  * @return DataObjec|DataList                DataObject/DataList result or stdClass on error
  */
 public function handleQuery(SS_HTTPRequest $request)
 {
     //get requested model(s) details
     $model = $request->param('ClassName');
     $id = $request->param('ID');
     $response = false;
     $queryParams = $this->parseQueryParameters($request->getVars());
     //validate Model name + store
     if ($model) {
         $model = $this->deSerializer->unformatName($model);
         if (!class_exists($model)) {
             return new RESTfulAPI_Error(400, "Model does not exist. Received '{$model}'.");
         } else {
             //store requested model data and query data
             $this->requestedData['model'] = $model;
         }
     } else {
         //if model missing, stop + return blank object
         return new RESTfulAPI_Error(400, "Missing Model parameter.");
     }
     //check API access rules on model
     if (!RESTfulAPI::api_access_control($model, $request->httpMethod())) {
         return new RESTfulAPI_Error(403, "API access denied.");
     }
     //validate ID + store
     if (($request->isPUT() || $request->isDELETE()) && !is_numeric($id)) {
         return new RESTfulAPI_Error(400, "Invalid or missing ID. Received '{$id}'.");
     } else {
         if ($id !== NULL && !is_numeric($id)) {
             return new RESTfulAPI_Error(400, "Invalid ID. Received '{$id}'.");
         } else {
             $this->requestedData['id'] = $id;
         }
     }
     //store query parameters
     if ($queryParams) {
         $this->requestedData['params'] = $queryParams;
     }
     //map HTTP word to module method
     switch ($request->httpMethod()) {
         case 'GET':
             return $this->findModel($model, $id, $queryParams, $request);
             break;
         case 'POST':
             return $this->createModel($model, $request);
             break;
         case 'PUT':
             return $this->updateModel($model, $id, $request);
             break;
         case 'DELETE':
             return $this->deleteModel($model, $id, $request);
             break;
         default:
             return new RESTfulAPI_Error(403, "HTTP method mismatch.");
             break;
     }
 }
 /**
  * @inheritdoc
  *
  * @param SS_HTTPRequest $request
  * @param Session $session
  * @param DataModel $model
  *
  * @return bool
  */
 public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
 {
     if (array_key_exists('flush', $request->getVars())) {
         foreach (ClassInfo::implementorsOf('Flushable') as $class) {
             $class::flush();
         }
     }
     return true;
 }
 /**
  * @param SS_HTTPRequest $request
  * @return string
  */
 function topics(SS_HTTPRequest $request)
 {
     $params = $request->getVars();
     $result = $this->course_topics_query->handle(new OpenStackImplementationNamesQuerySpecification($params["term"]));
     $res = array();
     foreach ($result->getResult() as $dto) {
         array_push($res, array('label' => $dto->getLabel(), 'value' => $dto->getValue()));
     }
     return json_encode($res);
 }
 /**
  * On every URL that generates a 404, we'll capture it here and see if we can
  * find an old URL that it should be redirecting to.
  *
  * @param SS_HTTPRequest $request The request object
  * @throws SS_HTTPResponse_Exception
  */
 public function onBeforeHTTPError404($request)
 {
     // We need to get the URL ourselves because $request->allParams() only has a max of 4 params
     $params = preg_split('|/+|', $request->getURL());
     $getvars = $request->getVars();
     unset($getvars['url']);
     $page = self::find_old_page($params);
     if ($page) {
         $res = new SS_HTTPResponse();
         $res->redirect(Controller::join_links($page, $getvars ? '?' . http_build_query($getvars) : null), 301);
         throw new SS_HTTPResponse_Exception($res);
     }
 }
 /**
  * @param    SS_HTTPRequest $request
  * @throws    MigrationException
  */
 public function run($request)
 {
     // Only allow execution from the command line (for simplicity and security).
     if (!Director::is_cli()) {
         echo "<p>Sorry, but this can only be run from the command line.</p>";
         return;
     }
     // Get and pre-process arguments. Format: ["argument" => true, "make" => "filename", ... ]
     $getVars = $request->getVars();
     $args = array();
     if (isset($getVars["args"]) && is_array($getVars["args"])) {
         foreach ($getVars["args"] as $arg) {
             // Separate keys/values.
             $argVals = explode(":", $arg, 2);
             $key = $argVals[0];
             $value = true;
             if (count($argVals) > 1) {
                 $value = $argVals[1];
             }
             $args[$key] = $value;
         }
     }
     // Unfortunately, SilverStripe is not using exceptions for database errors for some reason, so we must
     // temporarily setup our own global error handler as a stop gap so we can properly handle transactions.
     set_error_handler(function ($errno, $errstr) {
         throw new MigrationException($errstr, $errno);
     });
     // Use a shutdown function to help clean up and track final exit status, in case an unexpected fatal error occurs.
     $this->error = true;
     register_shutdown_function(array($this, "shutdown"));
     // Determine action to take. Wrap everything in a transaction so it can be rolled back in case of error.
     DB::getConn()->transactionStart();
     try {
         if (isset($args["up"])) {
             $this->up();
         } elseif (isset($args["down"])) {
             $this->down();
         } elseif (isset($args["make"])) {
             $this->make($args["make"]);
         } else {
             throw new MigrationException("Invalid or no migration arguments provided. Please specify either: 'up', 'down' or 'make:name_of_your_migration'.");
         }
         // Commit and clean up error state..
         DB::getConn()->transactionEnd();
         $this->error = false;
     } catch (Exception $e) {
         $this->shutdown($e);
     }
     // Shutdown method below will run next.
 }
 /**
  * On every URL that generates a 404, we'll capture it here and see if we can
  * find an old URL that it should be redirecting to.
  *
  * @param SS_HTTPRequest $request The request object
  * @throws SS_HTTPResponse_Exception
  */
 public function onBeforeHTTPError404($request)
 {
     // Build up the request parameters
     $params = array_filter(array_values($request->allParams()), function ($v) {
         return $v !== NULL;
     });
     $getvars = $request->getVars();
     unset($getvars['url']);
     $page = self::find_old_page($params);
     if ($page) {
         $res = new SS_HTTPResponse();
         $res->redirect(Controller::join_links($page, $getvars ? '?' . http_build_query($getvars) : null), 301);
         throw new SS_HTTPResponse_Exception($res);
     }
 }
Esempio n. 13
0
 /**
  * @param SS_HTTPRequest $request
  * @return $this
  * Handle signup type
  */
 public function index(SS_HTTPRequest $request)
 {
     $vars = $request->getVars();
     if (array_key_exists('power', $vars) && $vars['power']) {
         $data['type'] = 'PowerPlan';
         $data['id'] = $vars['power'];
         Session::set('Signup', $data);
     } elseif (array_key_exists('gas', $vars) && $vars['gas']) {
         $data['type'] = 'GasPlan';
         $data['id'] = $vars['gas'];
         Session::set('Signup', $data);
     } else {
         $this->redirect('home/result');
     }
     return $this;
 }
    /**
     * Process and render search results.
     *
     * @param array $data The raw request data submitted by user
     * @param SearchForm $form The form instance that was submitted
     * @param SS_HTTPRequest $request Request generated for this action
     */
    public function getSearchResults($request)
    {
        $list = new ArrayList();
        $v = $request->getVars();
        $q = $v["Search"];
        $input = DB::getConn()->addslashes($q);
        $data = DB::query(<<<EOF
SELECT
\t`pages`.`ID`,
\t`pages`.`ClassName`,
\t`pages`.`Title`,
\tGROUP_CONCAT(`do`.`Content` SEPARATOR ' ') as `Content`,
\t`pages`.`PageID`,
\tSUM(MATCH (`do`.`Title`, `do`.`Content`) AGAINST ('{$input}' IN NATURAL LANGUAGE MODE)) as `relevance`
FROM
\tSearchableDataObjects as `pages`
JOIN
\tSearchableDataObjects as `do`
ON
\t`pages`.`ID` = `do`.`OwnerID` AND
\t`pages`.`ClassName` = `do`.`OwnerClassName`
WHERE
\t`pages`.`ID` = `pages`.`OwnerID` AND
    `pages`.`ClassName` = `pages`.`OwnerClassName`
GROUP BY
\t`pages`.`ID`,
\t`pages`.`ClassName`
HAVING
\t`relevance`
ORDER BY
\t`relevance` DESC
EOF
);
        foreach ($data as $row) {
            $do = DataObject::get_by_id($row['ClassName'], $row['ID']);
            if (!$do) {
                continue;
            }
            $do->Title = $row['Title'];
            $do->Content = $row['Content'];
            $list->push($do);
        }
        $pageLength = Config::inst()->get('CustomSearch', 'items_per_page');
        $ret = new PaginatedList($list, $request);
        $ret->setPageLength($pageLength);
        return $ret;
    }
Esempio n. 15
0
 /**
  * On every URL that generates a 404, we'll capture it here and see if we can
  * find an old URL that it should be redirecting to.
  *
  * @param SS_HTTPRequest $request The request object
  * @throws SS_HTTPResponse_Exception
  */
 public function onBeforeHTTPError404($request)
 {
     // We need to get the URL ourselves because $request->allParams() only has a max of 4 params
     $params = preg_split('|/+|', $request->getURL());
     $cleanURL = trim(Director::makeRelative($request->getURL(false), '/'));
     $getvars = $request->getVars();
     unset($getvars['url']);
     $page = self::find_old_page($params);
     $cleanPage = trim(Director::makeRelative($page), '/');
     if (!$cleanPage) {
         $cleanPage = Director::makeRelative(RootURLController::get_homepage_link());
     }
     if ($page && $cleanPage != $cleanURL) {
         $res = new SS_HTTPResponse();
         $res->redirect(Controller::join_links($page, $getvars ? '?' . http_build_query($getvars) : null), 301);
         throw new SS_HTTPResponse_Exception($res);
     }
 }
 public function handleRequest(SS_HTTPRequest $request, DataModel $model = null)
 {
     self::$is_at_root = true;
     $this->setDataModel($model);
     $this->pushCurrent();
     $this->init();
     if (!($site = Multisites::inst()->getCurrentSiteId())) {
         return $this->httpError(404);
     }
     $page = SiteTree::get()->filter(array('ParentID' => $site, 'URLSegment' => 'home'));
     if (!($page = $page->first())) {
         return $this->httpError(404);
     }
     $request = new SS_HTTPRequest($request->httpMethod(), $page->RelativeLink(), $request->getVars(), $request->postVars());
     $request->match('$URLSegment//$Action', true);
     $front = new MultisitesFrontController();
     $response = $front->handleRequest($request, $model);
     $this->popCurrent();
     return $response;
 }
 public function getMembers(SS_HTTPRequest $request)
 {
     try {
         $query_string = $request->getVars();
         $query = Convert::raw2sql($query_string['query']);
         $summit_id = intval($request->param('SUMMIT_ID'));
         $summit = Summit::get_by_id('Summit', $summit_id);
         if (is_null($summit)) {
             throw new NotFoundEntityException('Summit', sprintf(' id %s', $summit_id));
         }
         $members = DB::query("SELECT M.ID AS id, CONCAT(M.FirstName,' ',M.Surname,' (',M.Email,')') AS name FROM Member AS M\n\n                                    WHERE\n                                    (\n                                      M.FirstName LIKE '%{$query}%' OR\n                                      M.Surname LIKE '%{$query}%' OR\n                                      M.Email LIKE '%{$query}%' OR\n                                      CONCAT(M.FirstName,' ',M.Surname) LIKE '%{$query}%'\n                                    )\n                                    AND\n                                    EXISTS\n                                    (\n                                      SELECT 1 FROM Group_Members AS GM\n                                      INNER JOIN `Group` AS G ON G.ID = GM.GroupID\n                                      WHERE\n                                      GM.MemberID = M.ID\n                                      AND\n                                      (\n                                        G.Code = '" . IFoundationMember::CommunityMemberGroupSlug . "'\n                                        OR\n                                        G.Code = '" . IFoundationMember::FoundationMemberGroupSlug . "'\n                                      )\n                                    )\n                                    ORDER BY M.FirstName, M.Surname LIMIT 25;");
         $data = array();
         foreach ($members as $member) {
             $data[] = $member;
         }
         return $this->ok($data);
     } catch (NotFoundEntityException $ex2) {
         SS_Log::log($ex2->getMessage(), SS_Log::WARN);
         return $this->notFound($ex2->getMessage());
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->serverError();
     }
 }
Esempio n. 18
0
 /**
  * Handle a form submission.  GET and POST requests behave identically.
  * Populates the form with {@link loadDataFrom()}, calls {@link validate()},
  * and only triggers the requested form action/method
  * if the form is valid.
  *
  * @param SS_HTTPRequest $request
  * @throws SS_HTTPResponse_Exception
  */
 public function httpSubmission($request)
 {
     // Strict method check
     if ($this->strictFormMethodCheck) {
         // Throws an error if the method is bad...
         if ($this->formMethod != $request->httpMethod()) {
             $response = Controller::curr()->getResponse();
             $response->addHeader('Allow', $this->formMethod);
             $this->httpError(405, _t("Form.BAD_METHOD", "This form requires a " . $this->formMethod . " submission"));
         }
         // ...and only uses the variables corresponding to that method type
         $vars = $this->formMethod == 'GET' ? $request->getVars() : $request->postVars();
     } else {
         $vars = $request->requestVars();
     }
     // Populate the form
     $this->loadDataFrom($vars, true);
     // Protection against CSRF attacks
     $token = $this->getSecurityToken();
     if (!$token->checkRequest($request)) {
         $securityID = $token->getName();
         if (empty($vars[$securityID])) {
             $this->httpError(400, _t("Form.CSRF_FAILED_MESSAGE", "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again."));
         } else {
             // Clear invalid token on refresh
             $data = $this->getData();
             unset($data[$securityID]);
             Session::set("FormInfo.{$this->FormName()}.data", $data);
             Session::set("FormInfo.{$this->FormName()}.errors", array());
             $this->sessionMessage(_t("Form.CSRF_EXPIRED_MESSAGE", "Your session has expired. Please re-submit the form."), "warning");
             return $this->controller->redirectBack();
         }
     }
     // Determine the action button clicked
     $funcName = null;
     foreach ($vars as $paramName => $paramVal) {
         if (substr($paramName, 0, 7) == 'action_') {
             // Break off querystring arguments included in the action
             if (strpos($paramName, '?') !== false) {
                 list($paramName, $paramVars) = explode('?', $paramName, 2);
                 $newRequestParams = array();
                 parse_str($paramVars, $newRequestParams);
                 $vars = array_merge((array) $vars, (array) $newRequestParams);
             }
             // Cleanup action_, _x and _y from image fields
             $funcName = preg_replace(array('/^action_/', '/_x$|_y$/'), '', $paramName);
             break;
         }
     }
     // If the action wasn't set, choose the default on the form.
     if (!isset($funcName) && ($defaultAction = $this->defaultAction())) {
         $funcName = $defaultAction->actionName();
     }
     if (isset($funcName)) {
         Form::set_current_action($funcName);
         $this->setButtonClicked($funcName);
     }
     // Permission checks (first on controller, then falling back to form)
     if ($this->controller->hasMethod($funcName) && !$this->controller->checkAccessAction($funcName) && !$this->actions->dataFieldByName('action_' . $funcName)) {
         return $this->httpError(403, sprintf('Action "%s" not allowed on controller (Class: %s)', $funcName, get_class($this->controller)));
     } elseif ($this->hasMethod($funcName) && !$this->checkAccessAction($funcName)) {
         return $this->httpError(403, sprintf('Action "%s" not allowed on form (Name: "%s")', $funcName, $this->name));
     }
     // TODO : Once we switch to a stricter policy regarding allowed_actions (meaning actions must be set
     // explicitly in allowed_actions in order to run)
     // Uncomment the following for checking security against running actions on form fields
     /* else {
     			// Try to find a field that has the action, and allows it
     			$fieldsHaveMethod = false;
     			foreach ($this->Fields() as $field){
     				if ($field->hasMethod($funcName) && $field->checkAccessAction($funcName)) {
     					$fieldsHaveMethod = true;
     				}
     			}
     			if (!$fieldsHaveMethod) {
     				return $this->httpError(
     					403,
     					sprintf('Action "%s" not allowed on any fields of form (Name: "%s")', $funcName, $this->Name())
     				);
     			}
     		}*/
     // Validate the form
     if (!$this->validate()) {
         return $this->getValidationErrorResponse();
     }
     // First, try a handler method on the controller (has been checked for allowed_actions above already)
     if ($this->controller->hasMethod($funcName)) {
         return $this->controller->{$funcName}($vars, $this, $request);
         // Otherwise, try a handler method on the form object.
     } elseif ($this->hasMethod($funcName)) {
         return $this->{$funcName}($vars, $this, $request);
     } elseif ($field = $this->checkFieldsForAction($this->Fields(), $funcName)) {
         return $field->{$funcName}($vars, $this, $request);
     }
     return $this->httpError(404);
 }
 /**
  * This acts the same as {@link Controller::handleRequest()}, but if an action cannot be found this will attempt to
  * fall over to a child controller in order to provide functionality for nested URLs.
  *
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request)
 {
     $child = null;
     $action = $request->param('Action');
     // If nested URLs are enabled, and there is no action handler for the current request then attempt to pass
     // control to a child controller. This allows for the creation of chains of controllers which correspond to a
     // nested URL.
     if ($action && SiteTree::nested_urls() && !$this->hasAction($action)) {
         // See ModelAdController->getNestedController() for similar logic
         Translatable::disable_locale_filter();
         // look for a page with this URLSegment
         $child = DataObject::get_one('SiteTree', sprintf("\"ParentID\" = %s AND \"URLSegment\" = '%s'", $this->ID, Convert::raw2sql($action)));
         Translatable::enable_locale_filter();
         // if we can't find a page with this URLSegment try to find one that used to have
         // that URLSegment but changed. See ModelAsController->getNestedController() for similiar logic.
         if (!$child) {
             $child = ModelAsController::find_old_page($action, $this->ID);
             if ($child) {
                 $response = new SS_HTTPResponse();
                 $params = $request->getVars();
                 if (isset($params['url'])) {
                     unset($params['url']);
                 }
                 $response->redirect(Controller::join_links($child->Link(Controller::join_links($request->param('ID'), $request->param('OtherID'))), $params ? '?' . http_build_query($params) : null), 301);
                 return $response;
             }
         }
     }
     // we found a page with this URLSegment.
     if ($child) {
         $request->shiftAllParams();
         $request->shift();
         $response = ModelAsController::controller_for($child)->handleRequest($request);
     } else {
         // If a specific locale is requested, and it doesn't match the page found by URLSegment,
         // look for a translation and redirect (see #5001). Only happens on the last child in
         // a potentially nested URL chain.
         if ($request->getVar('locale') && $this->dataRecord && $this->dataRecord->Locale != $request->getVar('locale')) {
             $translation = $this->dataRecord->getTranslation($request->getVar('locale'));
             if ($translation) {
                 $response = new SS_HTTPResponse();
                 $response->redirect($translation->Link(), 301);
                 throw new SS_HTTPResponse_Exception($response);
             }
         }
         Director::set_current_page($this->data());
         $response = parent::handleRequest($request);
         Director::set_current_page(null);
     }
     return $response;
 }
 public function exportReport(SS_HTTPRequest $request)
 {
     try {
         $query_string = $request->getVars();
         $sort = isset($query_string['sort']) ? Convert::raw2sql($query_string['sort']) : 'name';
         $sort_dir = isset($query_string['sort_dir']) ? Convert::raw2sql($query_string['sort_dir']) : 'ASC';
         $event_type = isset($query_string['event_type']) ? Convert::raw2sql($query_string['event_type']) : 'all';
         $venues = isset($query_string['venues']) ? $query_string['venues'] : '';
         $tracks = isset($query_string['tracks']) ? html_entity_decode($query_string['tracks']) : 'all';
         $start_date = isset($query_string['start_date']) && $query_string['start_date'] ? date('Y-m-d', strtotime($query_string['start_date'])) : '';
         $end_date = isset($query_string['end_date']) && $query_string['end_date'] ? date('Y-m-d', strtotime($query_string['end_date'])) : '';
         $search_term = isset($query_string['search_term']) ? $query_string['search_term'] : '';
         $report = $request->param('REPORT');
         $summit_id = intval($request->param('SUMMIT_ID'));
         $summit = $this->summit_repository->getById($summit_id);
         if (is_null($summit)) {
             throw new NotFoundEntityException('Summit', sprintf(' id %s', $summit_id));
         }
         $ext = 'csv';
         switch ($report) {
             case 'speaker_report':
                 $filter = isset($query_string['filter']) ? $query_string['filter'] : 'all';
                 $report_data = $this->assistance_repository->getAssistanceBySummit($summit_id, null, null, $sort, $sort_dir, $filter);
                 $data = $report_data['Data'];
                 $results = array();
                 foreach ($data as $row) {
                     array_push($results, $row);
                 }
                 $filename = "speaker_report-" . date('Ymd') . "." . $ext;
                 $delimiter = $ext == 'xls' ? "\t" : ",";
                 return CSVExporter::getInstance()->export($filename, $results, $delimiter);
                 break;
             case 'room_report':
                 $filename = "room_report-" . date('Ymd') . ".xlsx";
                 $objPHPExcel = new PHPExcel();
                 $objPHPExcel->getProperties()->setCreator("OpenStack");
                 $objPHPExcel->getProperties()->setTitle("Speaker Per Room Report");
                 $objPHPExcel->setActiveSheetIndex(0);
                 // sheet 1, key codes
                 $categories = $summit->Categories()->toArray();
                 $active_sheet = $objPHPExcel->getActiveSheet();
                 $active_sheet->setTitle("Key Codes");
                 $active_sheet->fromArray(array('Code', 'Category'), NULL, 'A1');
                 foreach ($categories as $key => $category) {
                     $row = $key + 2;
                     $active_sheet->SetCellValue('A' . $row, $category->Code);
                     $active_sheet->SetCellValue('B' . $row, $category->Title);
                 }
                 // day sheets
                 $days = $summit->getDates();
                 foreach ($days as $day) {
                     $active_sheet = $objPHPExcel->createSheet();
                     $active_sheet->setTitle(date('n-d', strtotime($day->Date)));
                     $active_sheet->fromArray(array('Date', 'Time', 'Code', 'Event', 'Room', 'Venue', 'Capacity', 'Speakers', 'Headcount', 'Total', 'Speaker Names'), NULL, 'A1');
                     $day_report = $this->assistance_repository->getRoomsBySummitAndDay($summit_id, $day->Date, $event_type, $venues);
                     foreach ($day_report as $key2 => $val) {
                         $row = $key2 + 2;
                         $start_time = $summit->convertDateFromUTC2TimeZone($val['start_date'], 'g:ia');
                         $end_time = $summit->convertDateFromUTC2TimeZone($val['end_date'], 'g:ia');
                         $date = $summit->convertDateFromUTC2TimeZone($val['start_date'], 'm/d/Y');
                         $time = $start_time . ' - ' . $end_time;
                         unset($val['start_date']);
                         unset($val['end_date']);
                         unset($val['id']);
                         $val['date'] = $date;
                         $val['time'] = $time;
                         $active_sheet->fromArray($val, NULL, 'A' . $row);
                     }
                 }
                 $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
                 header('Content-type: application/vnd.ms-excel');
                 header('Content-Disposition: attachment; filename="' . $filename . '"');
                 $objWriter->save('php://output');
                 return;
                 break;
             case 'presentation_report':
                 $search_term = isset($query_string['term']) ? Convert::raw2sql($query_string['term']) : '';
                 $filter = isset($query_string['filter']) ? $query_string['filter'] : 'all';
                 $report_data = $this->assistance_repository->getPresentationsAndSpeakersBySummit($summit_id, null, null, $sort, $sort_dir, $search_term, $filter);
                 $data = $report_data['Data'];
                 $results = array();
                 foreach ($data as $row) {
                     $row['start_date'] = $summit->convertDateFromUTC2TimeZone($row['start_date'], 'm/d/Y g:ia');
                     unset($row['presentation_id']);
                     unset($row['assistance_id']);
                     array_push($results, $row);
                 }
                 $filename = "presentations_report-" . date('Ymd') . "." . $ext;
                 $delimiter = $ext == 'xls' ? "\t" : ",";
                 return CSVExporter::getInstance()->export($filename, $results, $delimiter);
                 break;
             case 'video_report':
                 $filename = "video_report-" . date('Ymd') . ".xlsx";
                 $objPHPExcel = new PHPExcel();
                 $objPHPExcel->getProperties()->setCreator("OpenStack");
                 $objPHPExcel->getProperties()->setTitle("Video Output List");
                 // day sheets
                 $days = $summit->getDates();
                 foreach ($days as $day) {
                     $active_sheet = $objPHPExcel->createSheet();
                     $active_sheet->setTitle(date('n-d', strtotime($day->Date)));
                     $active_sheet->fromArray(array('Date', 'Time', 'Tags', 'Event', 'Description', 'Room', 'Venue', 'Display', 'YoutubeID'), NULL, 'A1');
                     $day_report = $this->assistance_repository->getPresentationMaterialBySummitAndDay($summit_id, $day->Date, $tracks, $venues, $start_date, $end_date, $search_term);
                     foreach ($day_report as $key2 => $val) {
                         $row = $key2 + 2;
                         $start_time = $summit->convertDateFromUTC2TimeZone($val['start_date'], 'g:ia');
                         $end_time = $summit->convertDateFromUTC2TimeZone($val['end_date'], 'g:ia');
                         $date = $summit->convertDateFromUTC2TimeZone($val['start_date'], 'm/d/Y');
                         $time = $start_time . ' - ' . $end_time;
                         unset($val['start_date']);
                         unset($val['end_date']);
                         unset($val['id']);
                         $val['date'] = $date;
                         $val['time'] = $time;
                         $val['tags'] .= ',' . $val['speakers'] . ',OpenStack Summit Austin';
                         unset($val['speakers']);
                         $active_sheet->fromArray($val, NULL, 'A' . $row);
                     }
                 }
                 $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
                 header('Content-type: application/vnd.ms-excel');
                 header('Content-Disposition: attachment; filename="' . $filename . '"');
                 $objWriter->save('php://output');
                 return;
                 break;
             case 'rsvp_report':
                 $search_term = isset($query_string['term']) ? Convert::raw2sql($query_string['term']) : '';
                 $events = $this->event_repository->searchBySummitTermAndHasRSVP($summit, $search_term);
                 if (count($events)) {
                     if (count($events) == 1) {
                         $results = array();
                         $event = array_pop($events);
                         list($rsvps, $total) = $this->rsvp_repository->getByEventPaged($event->ID, null, null);
                         $rsvp_array_template = array();
                         foreach ($event->RSVPTemplate()->Questions()->sort('Order') as $question) {
                             if ($question->Label) {
                                 $rsvp_array_template[$question->Label] = '';
                             }
                         }
                         if (count($rsvps)) {
                             foreach ($rsvps as $rsvp) {
                                 $rsvp_array = $rsvp_array_template;
                                 foreach ($rsvp->Answers() as $answer) {
                                     $rsvp_array[$answer->Question()->Label] = $answer->getFormattedAnswer();
                                 }
                                 $results[] = $rsvp_array;
                             }
                         }
                         $filename = "rsvp_report-" . date('Ymd') . "." . $ext;
                         $delimiter = $ext == 'xls' ? "\t" : ",";
                         return CSVExporter::getInstance()->export($filename, $results, $delimiter);
                     }
                 }
                 return $this->notFound();
                 break;
         }
         return $this->notFound();
     } catch (NotFoundEntityException $ex2) {
         SS_Log::log($ex2->getMessage(), SS_Log::WARN);
         return $this->notFound($ex2->getMessage());
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->serverError();
     }
 }
 /**
  *	Handle the current URL, parsing a year/month/day/media format, and directing towards any valid controller actions that may be defined.
  *
  *	@URLparameter <{YEAR}> integer
  *	@URLparameter <{MONTH}> integer
  *	@URLparameter <{DAY}> integer
  *	@URLparameter <{MEDIA_URL_SEGMENT}> string
  *	@return ss http response
  */
 public function handleURL()
 {
     // Retrieve the formatted URL.
     $request = $this->getRequest();
     $URL = $request->param('URL');
     // Determine whether a controller action resolves.
     if ($this->hasAction($URL) && $this->checkAccessAction($URL)) {
         $output = $this->{$URL}($request);
         // The current request URL has been successfully parsed.
         while (!$request->allParsed()) {
             $request->shift();
         }
         return $output;
     } else {
         if (!is_numeric($URL)) {
             // Determine whether a media page child once existed, and redirect appropriately.
             $response = $this->resolveURL();
             if ($response) {
                 // The current request URL has been successfully parsed.
                 while (!$request->allParsed()) {
                     $request->shift();
                 }
                 return $response;
             } else {
                 // The URL doesn't resolve.
                 return $this->httpError(404);
             }
         }
     }
     // Determine the formatted URL segments.
     $segments = array($URL);
     $remaining = $request->remaining();
     if ($remaining) {
         $remaining = explode('/', $remaining);
         // Determine the media page child to display.
         $child = null;
         $action = null;
         // Iterate the formatted URL segments.
         $iteration = 1;
         foreach ($remaining as $segment) {
             if (is_null($action)) {
                 // Update the current request.
                 $request->shift();
                 if ($child) {
                     // Determine whether a controller action has been defined.
                     $action = $segment;
                     break;
                 } else {
                     if (!is_numeric($segment)) {
                         if ($iteration === 4) {
                             // The remaining URL doesn't match the month/day/media format.
                             return $this->httpError(404);
                         }
                         // Determine the media page child to display, using the URL segment and date.
                         $children = MediaPage::get()->filter(array('ParentID' => $this->data()->ID, 'URLSegment' => $segment));
                         if (!empty($segments)) {
                             // Apply a partial match against the date, since the previous URL segments may only contain the year/month.
                             $date = array();
                             foreach ($segments as $previous) {
                                 $date[] = str_pad($previous, 2, '0', STR_PAD_LEFT);
                             }
                             $children = $children->filter(array('Date:StartsWith' => implode('-', $date)));
                         }
                         $child = $children->first();
                         // Determine whether a media page child once existed, and redirect appropriately.
                         if (is_null($child)) {
                             $response = $this->resolveURL();
                             if ($response) {
                                 // The current request URL has been successfully parsed.
                                 while (!$request->allParsed()) {
                                     $request->shift();
                                 }
                                 return $response;
                             } else {
                                 // The URL doesn't match the month/day/media format.
                                 return $this->httpError(404);
                             }
                         }
                     }
                 }
             }
             $segments[] = $segment;
             $iteration++;
         }
         // Retrieve the media page child controller, and determine whether an action resolves.
         if ($child) {
             $controller = ModelAsController::controller_for($child);
             // Determine whether a controller action resolves.
             if (is_null($action)) {
                 return $controller;
             } else {
                 if ($controller->hasAction($action) && $controller->checkAccessAction($action)) {
                     $output = $controller->{$action}($request);
                     // The current request URL has been successfully parsed.
                     while (!$request->allParsed()) {
                         $request->shift();
                     }
                     return $output;
                 } else {
                     // The controller action doesn't resolve.
                     return $this->httpError(404);
                 }
             }
         }
     }
     // Retrieve the paginated children using the date filter segments.
     $request = new SS_HTTPRequest('GET', $this->Link(), array_merge($request->getVars(), array('from' => implode('-', $segments))));
     // The new request URL doesn't require parsing.
     while (!$request->allParsed()) {
         $request->shift();
     }
     // Handle the new request URL.
     return $this->handleRequest($request);
 }
 /**
  * Fetch one or all remote dump files and writes to local filesystem.
  *
  * If filename is supplied as getVar then only that file will be retrieved, otherwise all files which don't exist locally will be retrieved up to number getVar.
  *
  * If filename is supplied as getVar then file will overwrite existing file.
  *
  * SideEffects:
  *  Reads files from remote system.
  *  Writes files to local filesystem.
  *  Outputs results
  *
  * @param SS_HTTPRequest $request
  * @return int number of files fetched
  * @throws PermissionFailureException
  */
 public function fetch(SS_HTTPRequest $request)
 {
     $options = CollectionTools::options_from_array($request->getVars(), array('RemoteHost' => $request->getIP(), 'Path' => Replicant::asset_path(), 'FileName' => '', 'UserName' => null, 'Password' => null));
     $action = ReplicantActionFetch::create();
     $action->checkPerm()->update($options)->execute();
     return $action->format();
 }
 public function exportPresentationsCompanyReport(SS_HTTPRequest $request)
 {
     try {
         $query_string = $request->getVars();
         $sort = isset($query_string['sort']) ? Convert::raw2sql($query_string['sort']) : 'name';
         $sort_dir = isset($query_string['sort_dir']) ? Convert::raw2sql($query_string['sort_dir']) : 'ASC';
         $search_term = isset($query_string['term']) ? Convert::raw2sql($query_string['term']) : '';
         $summit_id = intval($request->param('SUMMIT_ID'));
         $summit = $this->summit_repository->getById($summit_id);
         if (is_null($summit)) {
             throw new NotFoundEntityException('Summit', sprintf(' id %s', $summit_id));
         }
         $ext = 'csv';
         $report_data = $this->presentation_repository->searchByCompanyPaged($summit_id, null, null, $sort, $sort_dir, $search_term);
         $filename = "presentations_company_report-" . date('Ymd') . "." . $ext;
         $delimiter = $ext == 'xls' ? "\t" : ",";
         return CSVExporter::getInstance()->export($filename, $report_data['Data'], $delimiter);
     } catch (NotFoundEntityException $ex2) {
         SS_Log::log($ex2->getMessage(), SS_Log::WARN);
         return $this->notFound($ex2->getMessage());
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->serverError();
     }
 }
 /**
  * Action: remove all of an item from the cart
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  */
 public function removeall($request)
 {
     if ($product = $this->buyableFromRequest()) {
         $this->cart->remove($product, null, $request->getVars());
     }
     $this->extend('updateRemoveAllResponse', $request, $response, $product);
     return $response ? $response : self::direct();
 }
 public function getEventbriteUnmatched(SS_HTTPRequest $request)
 {
     try {
         $query_string = $request->getVars();
         $page = isset($query_string['page']) ? Convert::raw2sql($query_string['page']) : '';
         $page_size = isset($query_string['items']) ? Convert::raw2sql($query_string['items']) : '';
         $search_term = isset($query_string['term']) ? Convert::raw2sql($query_string['term']) : '';
         $suggested_only = isset($query_string['filter_suggested']) ? Convert::raw2sql($query_string['filter_suggested']) : 0;
         $summit_id = intval($request->param('SUMMIT_ID'));
         $summit = $this->summit_repository->getById($summit_id);
         if (is_null($summit)) {
             throw new NotFoundEntityException('Summit', sprintf(' id %s', $summit_id));
         }
         list($attendees, $count) = $this->eventbriteattendee_repository->getUnmatchedPaged($search_term, $suggested_only, $page, $page_size);
         $attendees_array = array();
         foreach ($attendees as $attendee) {
             $attendees_array[] = array('name' => $attendee->FirstName . ' ' . $attendee->LastName, 'email' => $attendee->Email, 'eventbrite_id' => $attendee->ExternalAttendeeId, 'amount_paid' => $attendee->Price, 'external_ids' => $attendee->ExternalIds);
         }
         return $this->ok(array('attendees' => $attendees_array, 'count' => $count));
     } catch (NotFoundEntityException $ex2) {
         SS_Log::log($ex2->getMessage(), SS_Log::WARN);
         return $this->notFound($ex2->getMessage());
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->serverError();
     }
 }
 /**
  * @param SS_HTTPRequest $request
  * @return array
  */
 private function processRequestParameters(SS_HTTPRequest $request)
 {
     $params = array();
     if ($request != null) {
         $params = $request->allParams();
         $variables = $request->getVars();
         $params['startPosition'] = $params['ID'];
         if ($params['startPosition'] < 1) {
             $params['startPosition'] = 1;
         }
         if (isset($variables['searchTerm'])) {
             $params['searchTerm'] = $variables['searchTerm'];
         }
         if ($params['OtherID']) {
             $params['searchTerm'] = $params['OtherID'];
         }
     }
     return $params;
 }
 /**
  * Handle the response from off-site gateways.
  *
  * @param SS_HTTPRequest $request
  * @return null
  */
 public function doProcessPaymentRedirect(SS_HTTPRequest $request)
 {
     try {
         $data = $request->getVars();
         $data['Amount'] = $this->amount;
         $response = $this->gateway->completePurchase($data)->send();
         if ($response->isSuccessful()) {
             // Payment is complete
             $this->sessionMessage(_t('Omnipayable.SUCCESS', 'Payment successful!'), 'good');
             $this->extend('onPaymentSuccess');
         } else {
             // Payment failed
             $this->sessionMessage(_t('Omnipayable.FAILURE', '{message}', array('message' => $response->getMessage())), 'bad');
             $this->extend('onPaymentFailure');
         }
     } catch (Exception $exception) {
         // Log any errors and present a user friendly message
         SS_Log::log($exception, SS_Log::ERR);
         $this->sessionMessage(_t('Omnipayable.ERROR', 'There was an error processing your payment. Please try agian later.'), 'bad');
     }
     return $this->controller->redirectBack();
 }
Esempio n. 28
0
 public function getSponsorOptions(SS_HTTPRequest $request)
 {
     try {
         $query_string = $request->getVars();
         $query = Convert::raw2sql($query_string['query']);
         $summit_id = intval($request->param('SUMMIT_ID'));
         $event_id = intval($request->param('EVENT_ID'));
         $summit = $this->summit_repository->getById($summit_id);
         if (is_null($summit)) {
             throw new NotFoundEntityException('Summit', sprintf(' id %s', $summit_id));
         }
         $event = $this->summitevent_repository->getById($event_id);
         if (is_null($event)) {
             throw new NotFoundEntityException('SummitEvent', sprintf(' id %s', $event_id));
         }
         $sponsors = DB::query("SELECT C.ID AS id, C.Name AS name FROM Company AS C\n                                    WHERE C.Name LIKE '{$query}%'\n                                    ORDER BY C.Name");
         $json_array = array();
         foreach ($sponsors as $sponsor) {
             $json_array[] = $sponsor;
         }
         echo json_encode($json_array);
     } catch (NotFoundEntityException $ex2) {
         SS_Log::log($ex2->getMessage(), SS_Log::WARN);
         return $this->notFound($ex2->getMessage());
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->serverError();
     }
 }
 /**
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model = null)
 {
     self::$is_at_root = true;
     $this->setDataModel($model);
     $this->pushCurrent();
     $this->init();
     if (!DB::isActive() || !ClassInfo::hasTable('SiteTree')) {
         $this->response = new SS_HTTPResponse();
         $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
         return $this->response;
     }
     $request = new SS_HTTPRequest($request->httpMethod(), self::get_homepage_link() . '/', $request->getVars(), $request->postVars());
     $request->match('$URLSegment//$Action', true);
     $controller = new ModelAsController();
     $result = $controller->handleRequest($request, $model);
     $this->popCurrent();
     return $result;
 }
 /**
  * @param SS_HTTPRequest $r
  * @return mixed
  */
 public function handleSpeakers(SS_HTTPRequest $r)
 {
     return $this->respondJSON($this->backend->getSpeakers($r->getVars()));
 }