protected function getHTTPRequest($method = 'GET', $class = 'ApiTest_Book', $id = '', $params = array())
 {
     $request = new SS_HTTPRequest($method, 'api/' . $class . '/' . $id, $params);
     $request->match($this->url_pattern);
     $request->setRouteParams(array('Controller' => 'RESTfulAPI'));
     return $request;
 }
 public function show(SS_HTTPRequest $request)
 {
     $root = $this->readFolder($this->Folder);
     $folderPath = "";
     if (is_null($request->param('Action'))) {
         $folder = $root;
     } else {
         foreach ($request->latestParams() as $param) {
             if (!is_null($param)) {
                 $folderPath .= "/" . $param;
             }
         }
         $folder = $this->readFolder($folderPath);
     }
     if (class_exists("BreadcrumbNavigation") && isset($folder)) {
         $parentFolders = explode("/", $folderPath);
         $parents = array_reverse($folder->parentStack());
         for ($i = 1; $i < count($parents); $i++) {
             $parents[$i]->markExpanded();
             $parents[$i]->markOpened();
             if ($i > 0) {
                 $do = new DataObject();
                 $do->Link = $parents[$i]->AbsoluteLink();
                 $do->MenuTitle = $parents[$i]->MenuTitle();
                 if ($i == count($parents) - 1) {
                     $do->isSelf = true;
                 }
                 $this->owner->AddBreadcrumbAfter($do);
             }
         }
         $this->MetaTitle = "Gallery: " . $parents[count($parents) - 1]->MenuTitle();
     }
     return $this->customise(array('Content' => $this->customise(array('RootFolder' => $root, 'CurrentFolder' => $folder))->renderWith('AssetsGalleryMain', 'Page'), 'Form' => ''));
 }
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     if (!$request) {
         user_error("Controller::handleRequest() not passed a request!", E_USER_ERROR);
     }
     $this->urlParams = $request->allParams();
     $this->request = $request;
     $this->setDataModel($model);
     // Find our action or set to index if not found
     $action = $this->request->param("Action");
     if (!$action) {
         $action = "index";
     }
     $result = $this->{$action}($request);
     // Try to determine what response we are dealing with
     if ($result instanceof SS_HTTPResponse) {
         $this->response = $result;
     } else {
         $this->response = new SS_HTTPResponse();
         $this->response->setBody($result);
     }
     // If we had a redirection or something, halt processing.
     if ($this->response->isFinished()) {
         return $this->response;
     }
     ContentNegotiator::process($this->response);
     HTTP::add_cache_headers($this->response);
     return $this->response;
 }
 public function index(SS_HTTPRequest $request)
 {
     if ($request->isPOST()) {
         $update = json_decode($request->getBody());
         $joblog = TranscodeJob::get()->filter('JobID', (int) $update->id)->first();
         // return if status already is done (some protection)
         if ($joblog->JobStatus !== "started") {
             return "Error: job status not started";
         }
         // save full update into log object -- no, may contain passwords etc. -- well, fixed but still...
         //format_id
         // load files into appropriate relations
         $transcodable = $joblog->Transcodable();
         $transcodable->loadTranscodedFiles();
         if (count(get_object_vars($update->errors))) {
             $joblog->JobErrorMessage = json_encode($update->errors);
             $joblog->JobStatus = "error";
         } else {
             if ($transcodable->transcodingComplete()) {
                 // set status to done when complete...
                 $joblog->JobErrorMessage = "";
                 $joblog->JobStatus = "done";
             }
         }
         // write logfile
         $joblog->write();
     } else {
         // this shouldn't happen
         return "Well hello there...";
     }
     return "Updated";
 }
 /**
  * 
  * @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');
         }
     }
 }
    public function testIndex()
    {
        $logger = $this->getMock('Psr\\Log\\LoggerInterface');
        $logger->expects($this->once())->method('info');
        $controller = new Controller($logger);
        $prop = new \ReflectionProperty(__NAMESPACE__ . '\\Controller', 'response');
        $prop->setAccessible(true);
        $prop->setValue($controller, new \SS_HTTPResponse());
        $req = new \SS_HTTPRequest('GET', '/');
        $req->setBody(<<<JSON
{
  "csp-report": {
    "document-uri": "http://example.com/signup.html",
    "referrer": "",
    "blocked-uri": "http://example.com/css/style.css",
    "violated-directive": "style-src cdn.example.com",
    "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports"
  }
}
JSON
);
        $response = $controller->index($req);
        $this->assertEquals(204, $response->getStatusCode());
        $this->assertEquals('', $response->getBody());
    }
 /**
  * This may need to be optimised. We'll just have to see how it performs.
  *
  * @param SS_HTTPRequest $req
  * @return array
  */
 public function downloads(SS_HTTPRequest $req)
 {
     $downloads = new ArrayList();
     $member = Member::currentUser();
     if (!$member || !$member->exists()) {
         $this->httpError(401);
     }
     // create a dropdown for sorting
     $sortOptions = Config::inst()->get('DownloadableAccountPageController', 'sort_options');
     if ($sortOptions) {
         $sort = $req->requestVar('sort');
         if (empty($sort)) {
             reset($sortOptions);
             $sort = key($sortOptions);
         }
         $sortControl = new DropdownField('download-sort', 'Sort By:', $sortOptions, $sort);
     } else {
         $sort = 'PurchaseDate';
         $sortControl = '';
     }
     // create a list of downloads
     $orders = $member->getPastOrders();
     if (!empty($orders)) {
         foreach ($orders as $order) {
             if ($order->DownloadsAvailable()) {
                 $downloads->merge($order->getDownloads());
             }
         }
     }
     Requirements::javascript(SHOP_DOWNLOADABLE_FOLDER . '/javascript/AccountPage_downloads.js');
     return array('Title' => 'Digital Purchases', 'Content' => '', 'SortControl' => $sortControl, 'HasDownloads' => $downloads->count() > 0, 'Downloads' => $downloads->sort($sort));
 }
 protected static function getDefault(SS_HTTPRequest $request, $var, $default)
 {
     if ($value = $request->getVar($var)) {
         return $value;
     }
     return $default;
 }
 /**
  * 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();
     }
 }
 /**
  * @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 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'));
 }
 public function getGoogleMapPin(SS_HTTPRequest $request)
 {
     $color = Convert::raw2sql($request->param('Color'));
     $path = ASSETS_PATH . '/maps/pins';
     // create folder on assets if does not exists ....
     if (!is_dir($path)) {
         mkdir($path, $mode = 0775, $recursive = true);
     }
     // if not get it from google (default)
     $ping_url = "http://chart.apis.google.com/chart?cht=mm&chs=32x32&chco=FFFFFF,{$color},000000&ext=.png";
     $write_2_disk = true;
     if (file_exists($path . '/pin_' . $color . '.jpg')) {
         // if we have the file on assets use it
         $ping_url = $path . '/pin_' . $color . '.jpg';
         $write_2_disk = false;
     }
     $body = file_get_contents($ping_url);
     if ($write_2_disk) {
         file_put_contents($path . '/pin_' . $color . '.jpg', $body);
     }
     $ext = 'jpg';
     $response = new SS_HTTPResponse($body, 200);
     $response->addHeader('Content-Type', 'image/' . $ext);
     return $response;
 }
 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();
     }
 }
 /**
  * Due to a bug, this could be called twice before 4.0,
  * see https://github.com/silverstripe/silverstripe-framework/pull/5173
  *
  * @param SS_HTTPRequest $request
  * @param string $action
  */
 public function beforeCallActionHandler($request, $action)
 {
     // This could be called twice
     if ($this->owner->beforeCallActionHandlerCalled) {
         return;
     }
     // If we don't have an action, getViewer will be called immediatly
     // If we have custom routes, request action is different than action
     $allParams = $request->allParams();
     $requestAction = null;
     if (!empty($allParams['Action'])) {
         $requestAction = $allParams['Action'];
     }
     if (!$this->owner->hasMethod($action) || $requestAction && $requestAction != $action) {
         self::clearBuffer();
     }
     $class = get_class($this->owner);
     DebugBar::withDebugBar(function (DebugBar\DebugBar $debugbar) use($class, $action) {
         /* @var $timeData DebugBar\DataCollector\TimeDataCollector */
         $timeData = $debugbar['time'];
         if (!$timeData) {
             return;
         }
         if ($timeData->hasStartedMeasure("handle")) {
             $timeData->stopMeasure("handle");
         }
         $timeData->startMeasure("action", "{$class} action {$action}");
     });
     $this->owner->beforeCallActionHandlerCalled = true;
 }
 public function getEventsAction(SS_HTTPRequest $request)
 {
     // Search date
     $date = DBField::create_field("SS_Datetime", $request->param("SearchDate"));
     if (!$date->getValue()) {
         $date = SS_Datetime::now();
     }
     // Get event data
     $cache = SS_Cache::factory(self::EVENTS_CACHE_NAME);
     $cacheKey = $date->Format('Y_m_d');
     if ($result = $cache->load($cacheKey)) {
         $data = unserialize($result);
     } else {
         $data = EventsDataUtil::get_events_data_for_day($date);
         $cache->save(serialize($data), $cacheKey);
     }
     // Get init data
     if ($request->param("GetAppConfig")) {
         $cache = SS_Cache::factory(self::CONFIG_CACHE_NAME);
         $cacheKey = 'APP_CONFIG';
         if ($result = $cache->load($cacheKey)) {
             $configData = unserialize($result);
         } else {
             $configData = AppConfigDataUtil::get_config_data();
             $cache->save(serialize($configData), $cacheKey);
         }
         $data['appConfig'] = $configData;
     }
     return $this->sendResponse($data);
 }
 public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
 {
     if (defined('PROXY_CACHE_GENERATING') || isset($GLOBALS['__cache_publish']) || strpos($request->getURL(), 'admin/') !== false) {
         return;
     }
     $this->database = Db::getConn();
     $queries = $this->database->queryRecord;
     $dupes = $this->database->getDuplicateQueries();
     $str = "\n<!-- Total queries: " . count($queries) . "-->\n";
     $str .= "\n<!-- Duplicate queries: " . count($dupes) . "-->\n";
     $b = $response->getBody();
     if (strpos($b, '</html>')) {
         if (count($queries) > $this->queryThreshold) {
             // add a floating div with info about the stuff
             $buildQueryList = function ($source, $class) {
                 $html = '';
                 foreach ($source as $sql => $info) {
                     $html .= "\n<p class='{$class}' style='display: none; border-top: 1px dashed #000;'>{$info->count} : {$info->query}</p>\n";
                     if ($info->source) {
                         $html .= "\n<p class='{$class}' style='color: #a00; display: none; '>Last called from {$info->source}</p>\n";
                     }
                 }
                 return $html;
             };
             $html = $buildQueryList($queries, 'debug-query');
             $html .= $buildQueryList($dupes, 'debug-dupe-query');
             $div = '<div id="query-stat-debugger" ' . 'style="position: fixed; bottom: 0; right: 0; border: 2px solid red; background: #fff; ' . 'font-size: 8px; font-family: sans-serif; width: 100px; z-index: 2000; padding: 1em;' . 'overflow: auto; max-height: 500px;">' . '<p id="debug-all-queries-list">Total of ' . count($queries) . ' queries</p>' . '<p id="debug-dupe-queries-list">Total of ' . count($dupes) . ' duplicates</p>' . $html . '<script>' . 'jQuery("#debug-all-queries-list").click(function () {' . 'var elems = jQuery(this).parent().find(".debug-query");' . 'jQuery(this).parent().css("width", "40%");' . 'elems.toggle();' . '}); ' . 'jQuery("#debug-dupe-queries-list").click(function () {' . 'var elems = jQuery(this).parent().find(".debug-dupe-query");' . 'jQuery(this).parent().css("width", "40%");' . 'elems.toggle();' . '}); ' . '' . '' . '</script>' . '</div>';
             $b = str_replace('</body>', "{$div}</body>", $b);
         }
         $b = str_replace('</html>', "{$str}</html>", $b);
         $response->setBody($b);
     }
 }
 public function placeOrder(SS_HTTPRequest $request)
 {
     $eventbrite_event_header = $request->getHeader('X-Eventbrite-Event');
     if (!$eventbrite_event_header) {
         return $this->httpError(403);
     }
     if ($eventbrite_event_header !== 'order.placed') {
         return $this->httpError(403);
     }
     if (!$this->isJson()) {
         return $this->httpError(403);
     }
     $json_request = $this->getJsonRequest();
     if (!isset($json_request['config']) || !isset($json_request['api_url'])) {
         return $this->httpError(403);
     }
     $config = $json_request['config'];
     if (!isset($config['action']) || $config['action'] !== 'order.placed') {
         return $this->httpError(403);
     }
     $current_local_url = Controller::join_links(Director::absoluteBaseURL(), $request->getURL());
     if (!isset($config['endpoint_url']) || $config['endpoint_url'] !== $current_local_url) {
         return $this->httpError(403);
     }
     try {
         $this->manager->registerEvent('ORDER_PLACED', $json_request['api_url']);
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->httpError(500);
     }
     return true;
 }
 public function getMember(SS_HTTPRequest $request)
 {
     try {
         $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));
         }
         $member_id = intval($request->param('MEMBER_ID'));
         $member = Member::get_by_id('Member', $member_id);
         if (is_null($member)) {
             throw new NotFoundEntityException('Member', sprintf(' id %s', $member_id));
         }
         $speaker = $member->Speaker()->ID ? $member->Speaker()->toMap() : '';
         $affiliation = '';
         if ($affiliation_obj = $member->getCurrentAffiliation()) {
             $affiliation = $affiliation_obj->toMap();
             $affiliation['Company'] = array('id' => $affiliation_obj->Organization()->ID, 'name' => $affiliation_obj->Organization()->Name);
         }
         echo json_encode(array('speaker' => $speaker, 'affiliation' => $affiliation));
     } 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();
     }
 }
Example #19
0
 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;
 }
 /**
  * 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 handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     $this->pushCurrent();
     $this->urlParams = $request->allParams();
     $this->request = $request;
     $this->response = new SS_HTTPResponse();
     $this->setDataModel($model);
     $urlsegment = $request->param('URLSegment');
     $this->extend('onBeforeInit');
     $this->init();
     $this->extend('onAfterInit');
     // First check products against URL segment
     if ($product = Product::get()->filter(array('URLSegment' => $urlsegment, 'Disabled' => 0))->first()) {
         $controller = Catalogue_Controller::create($product);
     } elseif ($category = ProductCategory::get()->filter('URLSegment', $urlsegment)->first()) {
         $controller = Catalogue_Controller::create($category);
     } else {
         // If CMS is installed
         if (class_exists('ModelAsController')) {
             $controller = ModelAsController::create();
         }
     }
     $result = $controller->handleRequest($request, $model);
     $this->popCurrent();
     return $result;
 }
 /**
  * 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);
     }
 }
 /**
  * Process all incoming requests passed to this controller, checking
  * that the file exists and passing the file through if possible.
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     // Copied from Controller::handleRequest()
     $this->pushCurrent();
     $this->urlParams = $request->allParams();
     $this->request = $request;
     $this->response = new SS_HTTPResponse();
     $this->setDataModel($model);
     $url = array_key_exists('url', $_GET) ? $_GET['url'] : $_SERVER['REQUEST_URI'];
     // remove any relative base URL and prefixed slash that get appended to the file path
     // e.g. /mysite/assets/test.txt should become assets/test.txt to match the Filename field on File record
     $url = Director::makeRelative(ltrim(str_replace(BASE_URL, '', $url), '/'));
     $file = File::find($url);
     if ($this->canDownloadFile($file)) {
         // If we're trying to access a resampled image.
         if (preg_match('/_resampled\\/[^-]+-/', $url)) {
             // File::find() will always return the original image, but we still want to serve the resampled version.
             $file = new Image();
             $file->Filename = $url;
         }
         $this->extend('onBeforeSendFile', $file);
         return $this->sendFile($file);
     } else {
         if ($file instanceof File) {
             // Permission failure
             Security::permissionFailure($this, 'You are not authorised to access this resource. Please log in.');
         } else {
             // File doesn't exist
             $this->response = new SS_HTTPResponse('File Not Found', 404);
         }
     }
     return $this->response;
 }
 /**
  * Out of the box, the handler "CurrentForm" value, which will return the rendered form.  
  * Non-Ajax calls will redirect back.
  * 
  * @param SS_HTTPRequest $request 
  * @param array $extraCallbacks List of anonymous functions or callables returning either a string
  * or SS_HTTPResponse, keyed by their fragment identifier. The 'default' key can
  * be used as a fallback for non-ajax responses.
  * @param array $fragmentOverride Change the response fragments.
  * @return SS_HTTPResponse
  */
 public function respond(SS_HTTPRequest $request, $extraCallbacks = array())
 {
     // Prepare the default options and combine with the others
     $callbacks = array_merge($this->callbacks, $extraCallbacks);
     $response = $this->getResponse();
     $responseParts = array();
     if (isset($this->fragmentOverride)) {
         $fragments = $this->fragmentOverride;
     } elseif ($fragmentStr = $request->getHeader('X-Pjax')) {
         $fragments = explode(',', $fragmentStr);
     } else {
         if ($request->isAjax()) {
             throw new SS_HTTPResponse_Exception("Ajax requests to this URL require an X-Pjax header.", 400);
         }
         $response->setBody(call_user_func($callbacks['default']));
         return $response;
     }
     // Execute the fragment callbacks and build the response.
     foreach ($fragments as $fragment) {
         if (isset($callbacks[$fragment])) {
             $res = call_user_func($callbacks[$fragment]);
             $responseParts[$fragment] = $res ? (string) $res : $res;
         } else {
             throw new SS_HTTPResponse_Exception("X-Pjax = '{$fragment}' not supported for this URL.", 400);
         }
     }
     $response->setBody(Convert::raw2json($responseParts));
     $response->addHeader('Content-Type', 'text/json');
     return $response;
 }
 /**
  * @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]");
         }
     }
 }
 /**
  * Get the whole tree of a part of the tree via an AJAX request with empty / none item prepended.
  *
  * @param SS_HTTPRequest $request
  * @return string
  * for version 2.4 and later
  */
 public function tree(SS_HTTPRequest $request)
 {
     if ($ID = (int) $request->latestparam('ID')) {
         return parent::tree($request);
     } else {
         return $this->preTree() . parent::tree($request) . OptionalTreeDropdownField::$postTree;
     }
 }
Example #27
0
 /**
  * Delete a file
  *
  * @param SS_HTTPRequest
  */
 public function deletefile(SS_HTTPRequest $r)
 {
     if ($file = DataObject::get_by_id("File", (int) $r->requestVar('id'))) {
         $file->delete();
         return new SS_HTTPResponse("OK", 200);
     }
     return false;
 }
 public function show(SS_HTTPRequest $request)
 {
     $region = Region::get()->byID($request->param('ID'));
     if (!$region) {
         return $this->httpError(404, 'That region could not be found');
     }
     return array('Region' => $region, 'Title' => $region->Title);
 }
Example #29
0
 public function viewClass(SS_HTTPRequest $request)
 {
     $class = $request->param('Class');
     if (!class_exists($class)) {
         throw new Exception('CodeViewer->viewClass(): not passed a valid class to view (does the class exist?)');
     }
     return $this->customise(array('Content' => $this->testAnalysis(getClassFile($class))))->renderWith('CodeViewer');
 }
 /**
  * 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;
 }