Пример #1
0
 public function httpError($code, $message = null)
 {
     $response = new SS_HTTPResponse();
     $response->setStatusCode($code);
     $response->addHeader('Content-Type', 'text/html');
     return $response;
 }
 /**
  * Action to handle upload of a single file
  *
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  * @return SS_HTTPResponse
  */
 public function upload(SS_HTTPRequest $request)
 {
     if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
         return $this->httpError(403);
     }
     // Protect against CSRF on destructive action
     $token = $this->getForm()->getSecurityToken();
     if (!$token->checkRequest($request)) {
         return $this->httpError(400);
     }
     // Get form details
     $name = $this->getName();
     $postVars = $request->postVar($name);
     // Save the temporary file into a File object
     $uploadedFiles = $this->extractUploadedFileData($postVars);
     $firstFile = reset($uploadedFiles);
     $file = $this->saveTemporaryFile($firstFile, $error);
     if (empty($file)) {
         $return = array('error' => $error);
     } else {
         $return = $this->encodeFileAttributes($file);
     }
     // Format response with json
     $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
     $response->addHeader('Content-Type', 'text/plain');
     if (!empty($return['error'])) {
         $response->setStatusCode(200);
     }
     return $response;
 }
 public function handleRequest(SS_HTTPRequest $request, DataModel $model = NULL)
 {
     $body = null;
     $lang = i18n::get_locale();
     $path = Config::inst()->get('UniversalErrorPage', 'DefaultPath');
     if (!$path) {
         $path = $this->defaultErrorPagePath;
     }
     $forCode = Config::inst()->get('UniversalErrorPage', $this->ErrorCode);
     $localeForCode = preg_replace('/\\.([a-z]+)$/i', '-' . $lang . '.$1', $forCode);
     $errorPages = array($localeForCode, $forCode, $path . "error-{$this->ErrorCode}-{$lang}.html", $path . "error-{$this->ErrorCode}-{$lang}.php", $path . "error-{$lang}.html", $path . "error-{$lang}.php", $path . 'error.html', $path . 'error.php');
     $this->extend('updateHandleRequest', $errorPages);
     // now check if any of the pages exist
     foreach ($errorPages as $errorPage) {
         if (!$body && file_exists($errorPage)) {
             $ext = pathinfo($errorPage, PATHINFO_EXTENSION);
             if ($ext == 'php') {
                 ob_start();
                 include $errorPage;
                 $body = ob_get_clean();
             } else {
                 $body = file_get_contents($errorPage);
             }
             break;
         }
     }
     if ($body) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode($this->ErrorCode);
         $response->setBody($body);
         return $response;
     }
     return parent::handleRequest($request, $model);
 }
 public function OnSitePhoneForm()
 {
     $request = Session::get('Current.PresentationSpeakerSummitAssistanceConfirmationRequest');
     if (is_null($request)) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode(404);
         return $response;
     }
     $form = new OnSitePhoneForm($this, 'OnSitePhoneForm', $request);
     $form->loadDataFrom($request);
     return $form;
 }
 public function handleAssignBulkAction($gridField, $request)
 {
     $entity_id = $request->param('EntityID');
     $controller = $gridField->getForm()->Controller();
     $this->gridField = $gridField;
     $ids = $this->getRecordIDList();
     $this->processRecordIds($ids, $entity_id, $gridField, $request);
     $response = new SS_HTTPResponse(Convert::raw2json(array('done' => true, 'records' => $ids)));
     $response->addHeader('Content-Type', 'text/json');
     $response->setStatusCode(200);
     return $response;
 }
 public function member()
 {
     $EmailAddress = "";
     $Member = "";
     // Make sure the access is POST, not GET
     if (!$this->request->isPOST()) {
         return $this->httpError(403, 'Access Denied.');
     }
     if (!defined('APPSEC')) {
         return $this->httpError(403, 'Access Denied.');
     }
     // Make sure the APPSEC shared secret matches
     if ($this->request->postVar('APPSEC') != APPSEC) {
         return $this->httpError(403, 'Access Denied.');
     }
     // Pull email address from POST variables
     $EmailAddress = $this->request->postVar('email');
     // Sanitize the input
     $EmailAddress = convert::raw2sql($EmailAddress);
     // If an email address was provided, try to find a member with it
     if ($EmailAddress) {
         $Member = Member::get()->filter('Email', $EmailAddress)->first();
     }
     $response = new SS_HTTPResponse();
     // If a member was found return status 200 and 'OK'
     if ($Member && $Member->isFoundationMember()) {
         $response->setStatusCode(200);
         $response->setBody('OK');
         $response->output();
     } elseif ($EmailAddress) {
         $response->setStatusCode(404);
         $response->setBody('No Member Found.');
         $response->output();
     } else {
         $response->setStatusCode(500);
         $response->setBody('An error has occurred retrieving a member.');
         $response->output();
     }
 }
 protected function write(array $record)
 {
     ini_set('display_errors', 0);
     // TODO: This coupling isn't ideal
     // See https://github.com/silverstripe/silverstripe-framework/issues/4484
     if (\Controller::has_curr()) {
         $response = \Controller::curr()->getResponse();
     } else {
         $response = new SS_HTTPResponse();
     }
     // If headers have been sent then these won't be used, and may throw errors that we wont' want to see.
     if (!headers_sent()) {
         $response->setStatusCode($this->statusCode);
         $response->addHeader("Content-Type", $this->contentType);
     } else {
         // To supress errors aboot errors
         $response->setStatusCode(200);
     }
     $response->setBody($record['formatted']);
     $response->output();
     return false === $this->bubble;
 }
 public function handleDeleteAllSummitEntityEventsAction($gridField, $request)
 {
     $summit_id = intval($request->param("ID"));
     $controller = $gridField->getForm()->Controller();
     $this->gridField = $gridField;
     $summit = Summit::get()->byID($summit_id);
     $status = 404;
     if (!is_null($summit)) {
         $status = 200;
         DB::query("DELETE FROM SummitEntityEvent WHERE SummitID = {$summit_id} ;");
     }
     $response = new SS_HTTPResponse();
     $response->setStatusCode($status);
     return $response;
 }
Пример #9
0
 /**
  * Get a {@link SS_HTTPResponse} to response to a HTTP error code if an {@link ErrorPage} for that code is present.
  *
  * @param int $statusCode
  * @return SS_HTTPResponse
  */
 public static function response_for($statusCode)
 {
     // first attempt to dynamically generate the error page
     if ($errorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = {$statusCode}")) {
         return ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
     }
     // then fall back on a cached version
     $cachedPath = self::get_filepath_for_errorcode($statusCode, class_exists('Translatable') ? Translatable::get_current_locale() : null);
     if (file_exists($cachedPath)) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode($statusCode);
         $response->setBody(file_get_contents($cachedPath));
         return $response;
     }
 }
 /**
  * Filter executed AFTER a request
  *
  * @param SS_HTTPRequest $request Request container object
  * @param SS_HTTPResponse $response Response output object
  * @param DataModel $model Current DataModel
  * @return boolean Whether to continue processing other filters. Null or true will continue processing (optional)
  */
 public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     $code = $response->getStatusCode();
     $error_page_path = Director::baseFolder() . "/errors_pages/ui/{$code}/index.html";
     if (!$request->isAjax() && file_exists($error_page_path)) {
         //clean buffer
         ob_clean();
         $page_file = fopen($error_page_path, "r") or die("Unable to open file!");
         $body = fread($page_file, filesize($error_page_path));
         fclose($page_file);
         // set content type
         $response->addHeader('Content-Type', 'text/html');
         $response->setBody($body);
         $response->setStatusCode(200);
         return true;
     }
     return true;
 }
 public function processform(SS_HTTPRequest $r)
 {
     $entry = BlogEntry::create();
     if ($this->request->postVar('Title') != null) {
         $entry->Title = $this->request->postVar('Title');
         $entry->Content = $this->request->postVar('Content');
         $entry->Tags = $this->request->postVar('Tags');
         $entry->Date = $this->request->postVar('Date');
         $entry->ParentID = $this->request->postVar('ParentID');
         $entry->write();
         $entry->publish('Stage', 'Live');
         $response = new SS_HTTPResponse(_t('Dashboard.Success', 'Successfully Published'), '200');
         $response->setStatusCode(200, _t('Dashboard.Posted', 'Blog Post Published'));
         return $response;
     } else {
         user_error('Blog Title and Content must be present', E_USER_ERROR);
     }
 }
Пример #12
0
 /**
  * Get a {@link SS_HTTPResponse} to response to a HTTP error code if an
  * {@link ErrorPage} for that code is present. First tries to serve it 
  * through the standard SilverStripe request method. Falls back to a static
  * file generated when the user hit's save and publish in the CMS
  *
  * @param int $statusCode
  *
  * @return SS_HTTPResponse
  */
 public static function response_for($statusCode)
 {
     // first attempt to dynamically generate the error page
     $errorPage = ErrorPage::get()->filter(array("ErrorCode" => $statusCode))->first();
     if ($errorPage) {
         Requirements::clear();
         Requirements::clear_combined_files();
         return ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
     }
     // then fall back on a cached version
     $cachedPath = self::get_filepath_for_errorcode($statusCode, class_exists('Translatable') ? Translatable::get_current_locale() : null);
     if (file_exists($cachedPath)) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode($statusCode);
         $response->setBody(file_get_contents($cachedPath));
         return $response;
     }
 }
    public function handleGetAttendeesAction($gridField, $request)
    {
        if (!Permission::check('ADMIN')) {
            return new SS_HTTPResponse(null, 403);
        }
        $term = Convert::raw2sql($request->getVar('term'));
        $summit_id = intval($request->param("ID"));
        $result = array();
        $sql = <<<SQL
SELECT A.ID,  CONCAT(M.FirstName,' ',M.Surname) AS FullName, M.Email  FROM SummitAttendee A INNER JOIN
Member M on M.ID = A.MemberID
WHERE A.SummitID = {$summit_id}
HAVING FullName LIKE '%{$term}%' OR M.Email LIKE '%{$term}% LIMIT 10;';
SQL;
        foreach (DB::query($sql) as $row) {
            array_push($result, array('id' => $row['ID'], 'label' => $row['FullName'] . ' ( ' . $row['Email'] . ' )'));
        }
        $response = new SS_HTTPResponse(Convert::raw2json($result));
        $response->addHeader('Content-Type', 'text/json');
        $response->setStatusCode(200);
        return $response;
    }
 /**
  *	Display an error page on invalid request.
  *
  *	@parameter <{ERROR_CODE}> integer
  *	@parameter <{ERROR_MESSAGE}> string
  */
 public function httpError($code, $message = null)
 {
     // Determine the error page for the given status code.
     $errorPages = ClassInfo::exists('SiteTree') ? ErrorPage::get()->filter('ErrorCode', $code) : null;
     // Allow extension customisation.
     $this->extend('updateErrorPages', $errorPages);
     // Retrieve the error page response.
     if ($errorPages && ($errorPage = $errorPages->first())) {
         Requirements::clear();
         Requirements::clear_combined_files();
         $response = ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
         throw new SS_HTTPResponse_Exception($response, $code);
     } else {
         if ($errorPages && file_exists($cachedPage = ErrorPage::get_filepath_for_errorcode($code, class_exists('Translatable') ? Translatable::get_current_locale() : null))) {
             $response = new SS_HTTPResponse();
             $response->setStatusCode($code);
             $response->setBody(file_get_contents($cachedPage));
             throw new SS_HTTPResponse_Exception($response, $code);
         } else {
             return parent::httpError($code, $message);
         }
     }
 }
 /**
  * Copied and adjusted from HTTP::add_cache_headers
  *
  * @param Object $originator
  * @param SS_HTTPRequest $request
  * @param SS_HTTPResponse $response
  * @param DataModel $model
  */
 public function applyToResponse($originator, SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     $cacheAge = $this->cacheAge;
     // Development sites have frequently changing templates; this can get stuffed up by the code
     // below.
     if (Director::isDev()) {
         $cacheAge = 0;
     }
     // Populate $responseHeaders with all the headers that we want to build
     $responseHeaders = array();
     if (function_exists('apache_request_headers')) {
         $requestHeaders = apache_request_headers();
         if (isset($requestHeaders['X-Requested-With']) && $requestHeaders['X-Requested-With'] == 'XMLHttpRequest') {
             $cacheAge = 0;
         }
         // bdc: now we must check for DUMB IE6:
         if (isset($requestHeaders['x-requested-with']) && $requestHeaders['x-requested-with'] == 'XMLHttpRequest') {
             $cacheAge = 0;
         }
     }
     if ($cacheAge > 0) {
         $responseHeaders["Cache-Control"] = "max-age=" . $cacheAge . ", must-revalidate, no-transform";
         $responseHeaders["Pragma"] = "";
         $responseHeaders['Vary'] = $this->vary;
     } else {
         if ($response) {
             // Grab header for checking. Unfortunately HTTPRequest until 3.1 uses a mistyped variant.
             $contentDisposition = $response->getHeader('Content-disposition');
             if (!$contentDisposition) {
                 $contentDisposition = $response->getHeader('Content-Disposition');
             }
         }
         if ($response && Director::is_https() && strstr($_SERVER["HTTP_USER_AGENT"], 'MSIE') == true && strstr($contentDisposition, 'attachment;') == true) {
             // IE6-IE8 have problems saving files when https and no-cache are used
             // (http://support.microsoft.com/kb/323308)
             // Note: this is also fixable by ticking "Do not save encrypted pages to disk" in advanced options.
             $responseHeaders["Cache-Control"] = "max-age=3, must-revalidate, no-transform";
             $responseHeaders["Pragma"] = "";
         } else {
             $responseHeaders["Cache-Control"] = "no-cache, max-age=0, must-revalidate, no-transform";
         }
     }
     if (self::$modification_date && $cacheAge > 0) {
         $responseHeaders["Last-Modified"] = self::gmt_date(self::$modification_date);
         // Chrome ignores Varies when redirecting back (http://code.google.com/p/chromium/issues/detail?id=79758)
         // which means that if you log out, you get redirected back to a page which Chrome then checks against
         // last-modified (which passes, getting a 304)
         // when it shouldn't be trying to use that page at all because it's the "logged in" version.
         // By also using and etag that includes both the modification date and all the varies
         // values which we also check against we can catch this and not return a 304
         $etagParts = array(self::$modification_date, serialize($_COOKIE));
         $etagParts[] = Director::is_https() ? 'https' : 'http';
         if (isset($_SERVER['HTTP_USER_AGENT'])) {
             $etagParts[] = $_SERVER['HTTP_USER_AGENT'];
         }
         if (isset($_SERVER['HTTP_ACCEPT'])) {
             $etagParts[] = $_SERVER['HTTP_ACCEPT'];
         }
         $etag = sha1(implode(':', $etagParts));
         $responseHeaders["ETag"] = $etag;
         // 304 response detection
         if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
             $ifModifiedSince = strtotime(stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']));
             // As above, only 304 if the last request had all the same varies values
             // (or the etag isn't passed as part of the request - but with chrome it always is)
             $matchesEtag = !isset($_SERVER['HTTP_IF_NONE_MATCH']) || $_SERVER['HTTP_IF_NONE_MATCH'] == $etag;
             if ($ifModifiedSince >= self::$modification_date && $matchesEtag) {
                 if ($response) {
                     $response->setStatusCode(304);
                     $response->setBody('');
                 } else {
                     header('HTTP/1.0 304 Not Modified');
                     die;
                 }
             }
         }
         $expires = time() + $cacheAge;
         $responseHeaders["Expires"] = self::gmt_date($expires);
     }
     if (self::$etag) {
         $responseHeaders['ETag'] = self::$etag;
     }
     // Now that we've generated them, either output them or attach them to the SS_HTTPResponse as appropriate
     foreach ($responseHeaders as $k => $v) {
         $response->addHeader($k, $v);
     }
 }
Пример #16
0
 public function sendSignupConfirmation($request)
 {
     $body = $this->request->getBody();
     $json = json_decode($body, true);
     if (!$this->securityToken->checkRequest($request)) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode(403);
         $response->addHeader('Content-Type', 'application/json');
         $response->setBody(json_encode("Error"));
         return $response;
     }
     $this->securityToken->reset();
     $to = $json['email'];
     $news_update_email_from = defined('NEWS_UPDATE_EMAIL_FROM') ? NEWS_UPDATE_EMAIL_FROM : '*****@*****.**';
     $user_name = sprintf('%s %s', $json['first_name'], $json['last_name']);
     $email = EmailFactory::getInstance()->buildEmail('*****@*****.**', $to, 'Thank you for subscribing to OpenStack Foundation News updates');
     $email->setTemplate('NewsPageSignupConfirmationEMail');
     $email->populateTemplate(array('UserName' => $user_name, 'NewsUpdateEmailFrom' => $news_update_email_from));
     $email->send();
     return 'OK';
 }
Пример #17
0
 /**
  * Handles formatting and output error message
  * then exit.
  * 
  * @param  RESTfulAPI_Error $error Error object to return
  */
 public function error(RESTfulAPI_Error $error)
 {
     $answer = new SS_HTTPResponse();
     $body = $this->serializer->serialize($error->body);
     $answer->setBody($body);
     $answer->setStatusCode($error->code, $error->message);
     $answer->addHeader('Content-Type', $this->serializer->getcontentType());
     $answer = $this->setAnswerCORS($answer);
     // save controller's response then return/output
     $this->response = $answer;
     return $answer;
 }
Пример #18
0
 /**
  * Determines if a specified file exists
  * 
  * @param SS_HTTPRequest $request
  */
 public function fileexists(SS_HTTPRequest $request)
 {
     // Assert that requested filename doesn't attempt to escape the directory
     $originalFile = $request->requestVar('filename');
     if ($originalFile !== basename($originalFile)) {
         $return = array('error' => _t('File.NOVALIDUPLOAD', 'File is not a valid upload'));
     } else {
         $return = array('exists' => $this->checkFileExists($originalFile));
     }
     // Encode and present response
     $response = new SS_HTTPResponse(Convert::raw2json($return));
     $response->addHeader('Content-Type', 'application/json');
     if (!empty($return['error'])) {
         $response->setStatusCode(400);
     }
     return $response;
 }
Пример #19
0
 /**
  * Once the file has been uploaded to S3, the CMS will callback this action
  * and pass along details about the file that we'll use to create an S3File
  * DataObject.
  *
  * Will respond with an some JSON data about the new S3File DataObject so it
  * can be added to the Form to which our S3FileUploadField is attached.
  *
  * Most of this has been adapted from the uplaod action of the UploadField.
  * @param  SS_HTTPRequest $request
  * @return SS_HTTPResponse
  */
 public function upload(SS_HTTPRequest $request)
 {
     if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
         return $this->httpError(403);
     }
     // Protect against CSRF on destructive action
     $token = $this->getForm()->getSecurityToken();
     if (!$token->checkRequest($request)) {
         return $this->httpError(400);
     }
     // Get form details
     $postVars = $request->postVars();
     $postVars['LastModified'] = date("Y-m-d H:i:s", $postVars['LastModified']);
     $postVars['ETag'] = str_replace('"', '', $postVars['ETag']);
     $postVars['Region'] = $this->getRegion();
     // Create our S3File
     $s3File = new S3File($postVars);
     $s3File->write();
     $s3File->customise(array('UploadFieldDeleteLink' => $this->getItemHandler($s3File->ID)->DeleteLink()));
     // Format response with json
     $response = new SS_HTTPResponse(Convert::raw2json(array(array('bucket' => $s3File->Bucket, 'etag' => $s3File->ETag, 'id' => $s3File->ID, 'key' => $s3File->Key, 'last_modified' => $s3File->LastModified, 'location' => $s3File->Location, 'name' => $s3File->Name, 'size' => $s3File->Size, 'type' => $s3File->Type, 'fieldname' => $this->getName(), 'buttons' => (string) $s3File->renderWith($this->getTemplateFileButtons()), 'edit_url' => $this->getItemHandler($s3File->ID)->EditLink(), 'thumbnail_url' => $s3File->Icon()))));
     $response->addHeader('Content-Type', 'application/json');
     if (!empty($return['error'])) {
         $response->setStatusCode(403);
     }
     return $response;
 }
Пример #20
0
 public function getNavigationMenu()
 {
     $menu_html = $this->renderWith('Navigation_menu', array('WidgetCall' => true))->getValue();
     $data = array('html' => $menu_html);
     $jsonp = "jsonCallback(" . json_encode($data) . ")";
     $response = new SS_HTTPResponse();
     $response->setStatusCode(200);
     $response->addHeader('Content-Type', 'application/javascript');
     $response->setBody($jsonp);
     return $response;
 }
 /**
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse|void
  */
 public function upload(SS_HTTPRequest $request)
 {
     if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
         return $this->httpError(403);
     }
     // Protect against CSRF on destructive action
     $token = $this->getForm()->getSecurityToken();
     if (!$token->checkRequest($request)) {
         return $this->httpError(400);
     }
     // Get form details
     $name = $this->getName();
     $postVars = $request->postVar($name);
     // Save the temporary file into a File object
     $uploadedFiles = $this->extractUploadedFileData($postVars);
     $return = array('error' => 'The file upload was not successful');
     $uploadedFile = reset($uploadedFiles);
     $strClass = CloudinaryFile::GetCloudinaryFileForFile($uploadedFile['name']);
     $arrOptions = array();
     if ($strClass == 'CloudinaryVideo') {
         $arrOptions['resource_type'] = 'video';
     } elseif ($strClass == 'CloudinaryFile') {
         $arrOptions['resource_type'] = 'raw';
         $arrOptions['format'] = File::get_file_extension($uploadedFile['name']);
     }
     $arrUploaderDetails = \Cloudinary\Uploader::upload($uploadedFile['tmp_name'], $arrOptions);
     if ($arrUploaderDetails && is_array($arrUploaderDetails)) {
         if ($strClass == 'CloudinaryFile') {
             $arrPieces = explode('.', $arrUploaderDetails['public_id']);
             $strPublicID = isset($arrPieces[0]) ? $arrPieces[0] : '';
             $strFormat = isset($arrPieces[1]) ? $arrPieces[1] : '';
         } else {
             $strPublicID = $arrUploaderDetails['public_id'];
             $strFormat = $arrUploaderDetails['format'];
         }
         $arrData = array('Title' => $uploadedFile['name'], 'FileName' => $uploadedFile['name'], 'PublicID' => $strPublicID, 'Version' => $arrUploaderDetails['version'], 'Signature' => $arrUploaderDetails['signature'], 'URL' => $arrUploaderDetails['url'], 'SecureURL' => $arrUploaderDetails['secure_url'], 'FileType' => $arrUploaderDetails['resource_type'], 'FileSize' => $arrUploaderDetails['bytes'], 'Format' => $strFormat);
         if ($strClass == 'CloudinaryImage') {
             $arrData = array_merge($arrData, array('Width' => $arrUploaderDetails['width'], 'Height' => $arrUploaderDetails['height']));
         } else {
             if ($strClass == 'CloudinaryVideo') {
                 $arrData = array_merge($arrData, array('Width' => $arrUploaderDetails['width'], 'Height' => $arrUploaderDetails['height'], 'Duration' => $arrUploaderDetails['duration'], 'BitRate' => $arrUploaderDetails['bit_rate'], 'FrameRate' => $arrUploaderDetails['frame_rate']));
             }
         }
         $file = new $strClass($arrData);
         $file->write();
         $return = $this->encodeCloudinaryAttributes($file);
     }
     $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
     $response->addHeader('Content-Type', 'text/plain');
     if (!empty($return['error'])) {
         $response->setStatusCode(403);
     }
     return $response;
 }
 /**
  * Action to handle upload of a single file
  * 
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  * @return SS_HTTPResponse
  */
 public function upload(SS_HTTPRequest $request)
 {
     if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
         return $this->httpError(403);
     }
     // Protect against CSRF on destructive action
     $token = $this->getForm()->getSecurityToken();
     if (!$token->checkRequest($request)) {
         return $this->httpError(400);
     }
     // Get form details (name of the relation)
     $name = $this->getName();
     $postVars = $request->postVar($name);
     $uploadedFiles = $this->extractUploadedFileData($postVars);
     //
     // append all multiparts to one file here before proceeding
     //
     if ($request->getHeader('X-File-Name')) {
         // if chunked, get name from header
         //return Debug::dump($request->getHeader('X-File-Name'));
         $originalFileName = $request->getHeader('X-File-Name');
         $totalSize = $request->getHeader('X-File-Size');
         $uploadedChunkPath = $uploadedFiles[0]['tmp_name'];
         // We (mis)use the security ID as a way of 'unique-ifying' the temporary upload paths
         // so that we don't just depend on the original filename for this (or a scenario might
         // be possible to overwrite files based on an identical original name)
         // Added benefit it that the security ID will be different between form loads, which
         // makes the risk of appending to the same file over and over, a bit smaller
         $securityID = $request->postVar('SecurityID') ? $request->postVar('SecurityID') : 'none';
         // hash to prevent directory traversal etc posibilities based on original file name
         $temphash = sha1($securityID . $originalFileName);
         // eg /tmp/123somelonghash456 instead of $originalFileName.'.part'
         $tmpFilePath = dirname($uploadedChunkPath) . DIRECTORY_SEPARATOR . $temphash;
         $append = file_exists($tmpFilePath);
         // If it is the first chunk we have to create the file, othewise we append...
         // Note file_put_contents with FILE_APPEND produces overlapping chunks for some reason...
         $out_fp = fopen($tmpFilePath, $append ? "ab" : "wb");
         //append or write mode
         $in_fp = fopen($uploadedChunkPath, "rb");
         while ($buff = fread($in_fp, 4096)) {
             fwrite($out_fp, $buff);
         }
         fclose($out_fp);
         fclose($in_fp);
         // test if we're done with all chunks yet...
         //			$done = (filesize($tmpFilePath)==$totalSize ? true : false);
         if (filesize($tmpFilePath) == $totalSize) {
             // move file to last uploaded chunks tmp_filename
             // & set size etc for regular upload handling as if uploaded normally
             rename($tmpFilePath, $uploadedChunkPath);
             $uploadedFiles[0]['name'] = $originalFileName;
         } else {
             // not done yet, return for now...
             $return = array('ok' => '(' . $uploadedChunkPath . ' - ' . $tmpFilePath . ': ' . filesize($tmpFilePath) . '/' . $totalSize . ')');
             // Format response with json
             $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
             $response->addHeader('Content-Type', 'text/plain');
             return $response;
         }
     } else {
         $originalFile = $request->requestVar('filename');
     }
     // Multipart done (or small enough to have been done in one chunk)...
     // Save the temporary file into a File object
     $firstFile = reset($uploadedFiles);
     $file = $this->saveTemporaryFile($firstFile, $error);
     if (empty($file)) {
         $return = array('error' => $error);
     } else {
         $return = $this->encodeFileAttributes($file);
     }
     // Format response with json
     $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
     $response->addHeader('Content-Type', 'text/plain');
     if (!empty($return['error'])) {
         $response->setStatusCode(403);
     }
     return $response;
 }
Пример #23
0
 /**
  * @param Object $originator
  * @param SS_HTTPRequest $request
  * @param SS_HTTPResponse $response
  * @param DataModel $model
  */
 public function applyToResponse($originator, SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     $cacheAge = $this->cacheAge;
     $vary = $this->vary;
     $responseHeaders = array();
     // Allow overriding max-age from the object hooked up to the policed controller.
     if ($originator->hasMethod('getCacheAge')) {
         $extendedCacheAge = $originator->getCacheAge($cacheAge);
         if ($extendedCacheAge !== null) {
             $cacheAge = $extendedCacheAge;
         }
     }
     // Same for vary, but probably less useful.
     if ($originator->hasMethod('getVary')) {
         $extendedVary = $originator->getVary($vary);
         if ($extendedVary !== null) {
             $vary = $extendedVary;
         }
     }
     if ($cacheAge > 0) {
         // Note: must-revalidate means that the cache must revalidate AFTER the entry has gone stale.
         $responseHeaders["Cache-Control"] = "max-age=" . $cacheAge . ", must-revalidate, no-transform";
         $responseHeaders["Pragma"] = "";
         $responseHeaders['Vary'] = $vary;
         // Find out when the URI was last modified. Allows customisation, but fall back HTTP timestamp collector.
         if ($originator->hasMethod('getModificationTimestamp')) {
             $timestamp = $originator->getModificationTimestamp();
         } else {
             $timestamp = HTTP::$modification_date;
         }
         if ($timestamp) {
             $responseHeaders["Last-Modified"] = self::gmt_date($timestamp);
             // Chrome ignores Varies when redirecting back (http://code.google.com/p/chromium/issues/detail?id=79758)
             // which means that if you log out, you get redirected back to a page which Chrome then checks against
             // last-modified (which passes, getting a 304)
             // when it shouldn't be trying to use that page at all because it's the "logged in" version.
             // By also using and etag that includes both the modification date and all the varies
             // values which we also check against we can catch this and not return a 304
             $etagParts = array($timestamp, serialize($_COOKIE));
             $etagParts[] = Director::is_https() ? 'https' : 'http';
             if (isset($_SERVER['HTTP_USER_AGENT'])) {
                 $etagParts[] = $_SERVER['HTTP_USER_AGENT'];
             }
             if (isset($_SERVER['HTTP_ACCEPT'])) {
                 $etagParts[] = $_SERVER['HTTP_ACCEPT'];
             }
             $etag = sha1(implode(':', $etagParts));
             $responseHeaders['ETag'] = $etag;
             // 304 response detection
             if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
                 $ifModifiedSince = strtotime(stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']));
                 // As above, only 304 if the last request had all the same varies values
                 // (or the etag isn't passed as part of the request - but with chrome it always is)
                 $matchesEtag = !isset($_SERVER['HTTP_IF_NONE_MATCH']) || $_SERVER['HTTP_IF_NONE_MATCH'] == $etag;
                 if ($ifModifiedSince >= $timestamp && $matchesEtag) {
                     $response->setStatusCode(304);
                     $response->setBody('');
                 }
             }
             $expires = time() + $cacheAge;
             $responseHeaders['Expires'] = self::gmt_date($expires);
         }
     }
     if (self::$etag) {
         $responseHeaders['ETag'] = self::$etag;
     }
     // Now that we've generated them, either output them or attach them to the SS_HTTPResponse as appropriate
     foreach ($responseHeaders as $k => $v) {
         $response->addHeader($k, $v);
     }
 }
Пример #24
0
    /**
     * @param string $meta_tags
     * @return SS_HTTPResponse
     */
    private function buildOnlyMetaTagsResponse($meta_tags)
    {
        $response = new SS_HTTPResponse();
        $response->setStatusCode(200);
        $html = <<<APP_LINKS
               <html>
                <head>
                    {$meta_tags}
                </head>
                <body>
                </body>
                </html>
APP_LINKS;
        $response->setBody($html);
        return $response;
    }
 /**
  *	Attempt to redirect towards the highest priority link mapping that may have been defined.
  *
  *	@URLparameter direct <{BYPASS_LINK_MAPPINGS}> boolean
  */
 public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     // Bypass the request filter when requesting specific director rules such as "/admin" or "/dev".
     $requestURL = $request->getURL();
     $configuration = Config::inst();
     foreach ($configuration->get('Director', 'rules') as $segment => $controller) {
         // Retrieve the specific director rules.
         if (($position = strpos($segment, '$')) !== false) {
             $segment = rtrim(substr($segment, 0, $position), '/');
         }
         // Determine if the current request matches a specific director rule.
         if ($segment && strpos($requestURL, $segment) === 0) {
             // Continue processing the response.
             return true;
         }
     }
     // Bypass the request filter when using the direct GET parameter.
     if ($request->getVar('direct')) {
         // Continue processing the response.
         return true;
     }
     // Determine the default automated URL handling response status.
     $status = $response->getStatusCode();
     $success = $status >= 200 && $status < 300;
     $error = $status === 404;
     // Either hook into a page not found, or when enforced, replace the default automated URL handling.
     $enforce = $configuration->get('MisdirectionRequestFilter', 'enforce_misdirection');
     $replace = $configuration->get('MisdirectionRequestFilter', 'replace_default');
     if (($error || $enforce || $replace) && ($map = $this->service->getMappingByRequest($request))) {
         // Update the response code where appropriate.
         $responseCode = $map->ResponseCode;
         if ($responseCode == 0) {
             $responseCode = 303;
         } else {
             if ($responseCode == 301 && $map->ForwardPOSTRequest) {
                 $responseCode = 308;
             } else {
                 if ($responseCode == 303 && $map->ForwardPOSTRequest) {
                     $responseCode = 307;
                 }
             }
         }
         // Update the response using the link mapping redirection.
         $response->redirect($map->getLink(), $responseCode);
     } else {
         if ($error && ($fallback = $this->service->determineFallback($requestURL))) {
             // Update the response code where appropriate.
             $responseCode = $fallback['code'];
             if ($responseCode === 0) {
                 $responseCode = 303;
             }
             // Update the response using the fallback, enforcing no further redirection.
             $response->redirect(HTTP::setGetVar('direct', true, Controller::join_links(Director::absoluteBaseURL(), $fallback['link'])), $responseCode);
         } else {
             if (!$error && !$success && $replace) {
                 $response->setStatusCode(404);
                 // Retrieve the appropriate page not found response.
                 ClassInfo::exists('SiteTree') && ($page = ErrorPage::response_for(404)) ? $response->setBody($page->getBody()) : $response->setBody('No URL was matched!');
             }
         }
     }
     // Continue processing the response.
     return true;
 }
Пример #26
0
 /**
  * Action to handle removing a single file from the db relation
  * 
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  */
 public function remove(SS_HTTPRequest $request)
 {
     // Check form field state
     if ($this->parent->isDisabled() || $this->parent->isReadonly()) {
         return $this->httpError(403);
     }
     // Protect against CSRF on destructive action
     $token = $this->parent->getForm()->getSecurityToken();
     if (!$token->checkRequest($request)) {
         return $this->httpError(400);
     }
     $response = new SS_HTTPResponse();
     $response->setStatusCode(500);
     $fieldName = $this->parent->getName();
     $record = $this->parent->getRecord();
     $id = $this->getItem()->ID;
     if ($id && $record && $record->exists()) {
         if (($record->has_many($fieldName) || $record->many_many($fieldName)) && ($file = $record->{$fieldName}()->byID($id))) {
             $record->{$fieldName}()->remove($file);
             $response->setStatusCode(200);
         } elseif ($record->has_one($fieldName) && $record->{$fieldName . 'ID'} == $id) {
             $record->{$fieldName . 'ID'} = 0;
             $record->write();
             $response->setStatusCode(200);
         }
     }
     if ($response->getStatusCode() != 200) {
         $response->setStatusDescription(_t('UploadField.REMOVEERROR', 'Error removing file'));
     }
     return $response;
 }
 /**
  * @param $request
  * @return SS_HTTPResponse
  */
 public function searchOrg($request)
 {
     if (!Director::is_ajax()) {
         return $this->forbiddenError();
     }
     $term = $request->getVar('term');
     $term = Convert::raw2sql($term);
     $organizations = Org::get()->filter('Name:PartialMatch', $term)->limit(10);
     if ($organizations) {
         $suggestions = array();
         foreach ($organizations as $org) {
             array_push($suggestions, array('id' => $org->ID, 'label' => $org->Name, 'value' => $org->Name));
         }
         $response = new SS_HTTPResponse();
         $response->setStatusCode(200);
         $response->addHeader('Content-Type', 'application/json');
         $response->setBody(json_encode($suggestions));
         return $response;
     }
 }
 protected function addingDuplicate($msg)
 {
     // return a 401
     $response = new SS_HTTPResponse();
     $response->setStatusCode(409);
     $response->addHeader('Content-Type', 'application/json');
     $response->setBody(json_encode($msg));
     return $response;
 }
 /**
  * @return SS_HTTPResponse
  */
 function index()
 {
     $response = new SS_HTTPResponse();
     $result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
     if (!$result->ShouldPass()) {
         $response->setStatusCode($this->errorCode);
     }
     $resultText = $result->customise(array("URL" => Director::absoluteBaseURL(), "Title" => $this->title, "Name" => $this->checkSuiteName, "ErrorCode" => $this->errorCode))->renderWith("EnvironmentChecker");
     if (self::$email_results && !$result->ShouldPass()) {
         $email = new Email(self::$from_email_address, self::$to_email_address, $this->title, $resultText);
         $email->send();
     }
     // output the result as JSON if requested
     if ($this->getRequest()->getExtension() == 'json' || strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false) {
         $response->setBody($result->toJSON());
         $response->addHeader('Content-Type', 'application/json');
         return $response;
     }
     $response->setBody($resultText);
     return $response;
 }