Exemple #1
2
 function generatePDF()
 {
     // tempfolder
     $tmpBaseFolder = TEMP_FOLDER . '/shopsystem';
     $tmpFolder = project() ? "{$tmpBaseFolder}/" . project() : "{$tmpBaseFolder}/site";
     if (is_dir($tmpFolder)) {
         Filesystem::removeFolder($tmpFolder);
     }
     if (!file_exists($tmpFolder)) {
         Filesystem::makeFolder($tmpFolder);
     }
     $baseFolderName = basename($tmpFolder);
     //Get site
     Requirements::clear();
     $link = Director::absoluteURL($this->pdfLink() . "/?view=1");
     $response = Director::test($link);
     $content = $response->getBody();
     $content = utf8_decode($content);
     $contentfile = "{$tmpFolder}/" . $this->PublicURL . ".html";
     if (!file_exists($contentfile)) {
         // Write to file
         if ($fh = fopen($contentfile, 'w')) {
             fwrite($fh, $content);
             fclose($fh);
         }
     }
     return $contentfile;
 }
 public function testRenderTemplatePlaceholder()
 {
     // Create page object
     $page = $this->objFromFixture('Page', 'page1');
     $templateTitle = 'template1';
     $templatePlaceHolder = '{{' . $templateTitle . '}}';
     // Assert: render page
     $this->assertContains($templatePlaceHolder, $page->Content());
     // Create template
     $template = $this->objFromFixture('ViewTemplate', $templateTitle);
     $templatePlaceHolder = '{{' . $template->Title . '}}';
     // Page disable template view
     $page->EnableViewTemplate = false;
     // Assert: render page without view template
     $this->assertContains($templatePlaceHolder, $page->Content());
     // Page enable template view
     $page->EnableViewTemplate = true;
     // Assert: render page with view template
     $this->assertNotContains($templatePlaceHolder, $page->Content());
     // Login admin
     $this->logInWithPermission('ADMIN');
     // Assert: Publish page
     $published = $page->doPublish();
     $this->assertTrue($published);
     // Assert: page visible to public with render view template
     Member::currentUser()->logOut();
     $response = Director::test(Director::makeRelative($page->Link()));
     $this->assertNotContains($templatePlaceHolder, $response->getBody());
     $this->assertContains($template->ViewTemplate, $response->getBody());
 }
 /**
  *
  */
 function testBasicView()
 {
     // Confirm that this URL gets you the entire page, with the edit form loaded
     $response = Director::test('great-show');
     $this->assertTrue(strpos($response->getBody(), '<head') !== false);
     $this->assertTrue(strpos($response->getBody(), 'First Episode') !== false);
 }
Exemple #4
0
 /**
  * When an error page is published, create a static HTML page with its
  * content, so the page can be shown even when SilverStripe is not
  * functioning correctly before publishing this page normally.
  * @param string|int $fromStage Place to copy from. Can be either a stage name or a version number.
  * @param string $toStage Place to copy to. Must be a stage name.
  * @param boolean $createNewVersion Set this to true to create a new version number.  By default, the existing version number will be copied over.
  */
 function doPublish()
 {
     parent::doPublish();
     // Run the page (reset the theme, it might've been disabled by LeftAndMain::init())
     $oldTheme = SSViewer::current_theme();
     SSViewer::set_theme(SSViewer::current_custom_theme());
     $response = Director::test(Director::makeRelative($this->Link()));
     SSViewer::set_theme($oldTheme);
     $errorContent = $response->getBody();
     // Make the base tag dynamic.
     // $errorContent = preg_replace('/<base[^>]+href="' . str_replace('/','\\/', Director::absoluteBaseURL()) . '"[^>]*>/i', '<base href="$BaseURL" />', $errorContent);
     // Check we have an assets base directory, creating if it we don't
     if (!file_exists(ASSETS_PATH)) {
         mkdir(ASSETS_PATH, 02775);
     }
     // if the page is published in a language other than default language,
     // write a specific language version of the HTML page
     $filePath = self::get_filepath_for_errorcode($this->ErrorCode, $this->Locale);
     if ($fh = fopen($filePath, "w")) {
         fwrite($fh, $errorContent);
         fclose($fh);
     } else {
         $fileErrorText = sprintf(_t("ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions."), $errorFile);
         FormResponse::status_message($fileErrorText, 'bad');
         FormResponse::respond();
         return;
     }
 }
 /**
  * Perform an api request with the given options
  *
  * @param string $path the request path; can consist of resource name, identifier and GET params
  * @param array $options
  *  * string `body` the data
  *  * int `code` the expected response code
  *  * string `method` the http method
  *  * ApiSession `session` the test session
  * @return array
  * @throws SS_HTTPResponse_Exception
  */
 public function makeApiRequest($path, $options = [])
 {
     $settings = array_merge(['session' => null, 'token' => null, 'method' => 'GET', 'body' => null, 'code' => 200], $options);
     $response = Director::test(Controller::join_links($this->namespace, $path), null, $settings['session'], $settings['method'], $settings['body'], ['Authorization' => $settings['token'], 'Accept' => 'application/json']);
     $this->assertEquals($settings['code'], $response->getStatusCode(), "Wrong status code: {$response->getBody()}");
     return json_decode($response->getBody(), true);
 }
 /**
  * @todo Test the results of a publication better
  */
 function testPublish()
 {
     $page1 = $this->objFromFixture('Page', "page1");
     $page2 = $this->objFromFixture('Page', "page2");
     $this->session()->inst_set('loggedInAs', $this->idFromFixture('Member', 'admin'));
     $response = $this->get("admin/cms/publishall?confirm=1");
     $this->assertContains(sprintf(_t('CMSMain.PUBPAGES', "Done: Published %d pages"), 30), $response->getBody());
     // Some modules (e.g., cmsworkflow) will remove this action
     if (isset(CMSBatchActionHandler::$batch_actions['publish'])) {
         $response = Director::test("admin/cms/batchactions/publish", array('csvIDs' => implode(',', array($page1->ID, $page2->ID)), 'ajax' => 1), $this->session());
         $responseData = Convert::json2array($response->getBody());
         $this->assertTrue(property_exists($responseData['modified'], $page1->ID));
         $this->assertTrue(property_exists($responseData['modified'], $page2->ID));
     }
     // Get the latest version of the redirector page
     $pageID = $this->idFromFixture('RedirectorPage', 'page5');
     $latestID = DB::query('select max("Version") from "RedirectorPage_versions" where "RecordID"=' . $pageID)->value();
     $dsCount = DB::query('select count("Version") from "RedirectorPage_versions" where "RecordID"=' . $pageID . ' and "Version"=' . $latestID)->value();
     $this->assertEquals(1, $dsCount, "Published page has no duplicate version records: it has " . $dsCount . " for version " . $latestID);
     $this->session()->clear('loggedInAs');
     //$this->assertRegexp('/Done: Published 4 pages/', $response->getBody())
     /*
     $response = Director::test("admin/publishitems", array(
     	'ID' => ''
     	'Title' => ''
     	'action_publish' => 'Save and publish',
     ), $session);
     $this->assertRegexp('/Done: Published 4 pages/', $response->getBody())
     */
 }
 /**
  * Create an {@link ErrorPage} for status code 503
  * 
  * @see UnderConstruction_Extension::onBeforeInit()
  * @see DataObjectDecorator::requireDefaultRecords()
  * @return Void
  */
 function requireDefaultRecords()
 {
     // Ensure that an assets path exists before we do any error page creation
     if (!file_exists(ASSETS_PATH)) {
         mkdir(ASSETS_PATH);
     }
     $pageUnderConstructionErrorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = '503'");
     $pageUnderConstructionErrorPageExists = $pageUnderConstructionErrorPage && $pageUnderConstructionErrorPage->exists() ? true : false;
     $pageUnderConstructionErrorPagePath = ErrorPage::get_filepath_for_errorcode(503);
     if (!($pageUnderConstructionErrorPageExists && file_exists($pageUnderConstructionErrorPagePath))) {
         if (!$pageUnderConstructionErrorPageExists) {
             $pageUnderConstructionErrorPage = new ErrorPage();
             $pageUnderConstructionErrorPage->ErrorCode = 503;
             $pageUnderConstructionErrorPage->Title = _t('UnderConstruction.TITLE', 'Under Construction');
             $pageUnderConstructionErrorPage->Content = _t('UnderConstruction.CONTENT', '<p>Sorry, this site is currently under construction.</p>');
             $pageUnderConstructionErrorPage->Status = 'New page';
             $pageUnderConstructionErrorPage->write();
             $pageUnderConstructionErrorPage->publish('Stage', 'Live');
         }
         // Ensure a static error page is created from latest error page content
         $response = Director::test(Director::makeRelative($pageUnderConstructionErrorPage->Link()));
         if ($fh = fopen($pageUnderConstructionErrorPagePath, 'w')) {
             $written = fwrite($fh, $response->getBody());
             fclose($fh);
         }
         if ($written) {
             DB::alteration_message('503 error page created', 'created');
         } else {
             DB::alteration_message(sprintf('503 error page could not be created at %s. Please check permissions', $pageUnderConstructionErrorPagePath), 'error');
         }
     }
 }
Exemple #8
0
	/**
	 * Submit a post request
	 * @uses Director::test()
	 */
	function post($url, $data, $headers = null, $session = null, $body = null, $cookies = null) {
		$headers = (array) $headers;
		if($this->lastUrl) $headers['Referer'] = $this->lastUrl;
		$this->lastResponse = Director::test($url, $data, $session ? $session : $this->session, null, $body, $headers, $cookies);
		$this->lastUrl = $url;
		if(!$this->lastResponse) user_error("Director::test($url) returned null", E_USER_WARNING);
		return $this->lastResponse;
	}
Exemple #9
0
 /**
  * Submit a post request
  * @uses Director::test()
  */
 function post($url, $data, $headers = null)
 {
     $headers = $this->lastUrl ? array('Referer' => $this->lastUrl) : null;
     $this->lastResponse = Director::test($url, $data, $this->session, null, null, $headers);
     $this->lastUrl = $url;
     if (!$this->lastResponse) {
         user_error("Director::test({$url}) returned null", E_USER_WARNING);
     }
     return $this->lastResponse;
 }
	function testAllowedActions() {
		$response = Director::test("ControllerTest_SecuredController/methodaction");
		$this->assertEquals(200, $response->getStatusCode());
		
		$response = Director::test("ControllerTest_SecuredController/stringaction");
		$this->assertEquals(403, $response->getStatusCode());

		$response = Director::test("ControllerTest_SecuredController/adminonly");
		$this->assertEquals(403, $response->getStatusCode());
	}
 /**
  * Perform an api request with the given options
  *
  * @param string $path the request path; can consist of resource name, identifier and GET params
  * @param array $options
  *  * string `body` the data
  *  * int `code` the expected response code
  *  * string `method` the http method
  *  * ApiSession `session` the test session
  *  * string `token` the auth token
  *  * array `postVars` the post data, eg. multi form or files
  * @return array
  * @throws \SS_HTTPResponse_Exception
  */
 protected function makeApiRequest($path, $options = [])
 {
     $settings = array_merge(['session' => null, 'token' => null, 'method' => 'GET', 'body' => null, 'postVars' => null, 'code' => 200], $options);
     $headers = ['Accept' => 'application/json'];
     if ($settings['token']) {
         $headers['Authorization'] = "Bearer {$settings['token']}";
     }
     $response = \Director::test(\Controller::join_links($this->namespace, $path), $settings['postVars'], $settings['session'], $settings['method'], $settings['body'], $headers);
     $this->assertEquals($settings['code'], $response->getStatusCode(), "Wrong status code: {$response->getBody()}");
     return json_decode($response->getBody(), true);
 }
 function testLinksent()
 {
     $url1 = 'unsubscribe/linksent?SendEmail=normann1@silverstripe.com';
     $url2 = 'unsubscribe/linksent?SendError=normann1@silverstripe.com';
     $body1 = Director::test($url1)->getBody();
     $body2 = Director::test($url2)->getBody();
     $message1 = sprintf(_t('Unsubscribe.LINKSENTTO', "The unsubscribe link has been sent to %s"), '*****@*****.**');
     $message2 = sprintf(_t('Unsubscribe.LINKSENDERR', "Sorry, currently we have internal error, and can't send the unsubscribe link to %s"), '*****@*****.**');
     $this->AssertContains($message1, $body1);
     $this->AssertContains($message2, $body2);
 }
 function testDeleteComment()
 {
     $firstPage = $this->objFromFixture('Page', 'first');
     $this->autoFollowRedirection = false;
     $this->logInAs('commentadmin');
     $firstComment = $this->objFromFixture('Comment', 'firstComA');
     $firstCommentID = $firstComment->ID;
     Director::test($firstPage->RelativeLink(), null, $this->session());
     $delete = $this->get('CommentingController/delete/' . $firstComment->ID);
     $this->assertFalse(DataObject::get_by_id('Comment', $firstCommentID));
 }
 /**
  * Test generation of the view
  */
 function testBasicView()
 {
     Subsite::$write_hostmap = false;
     $subsite1ID = $this->objFromFixture('Subsite', 'domaintest1')->ID;
     // Open the admin area logged in as admin
     $response1 = Director::test('admin/subsites/', null, $this->adminLoggedInSession());
     // Confirm that this URL gets you the entire page, with the edit form loaded
     $response2 = Director::test("admin/subsites/Subsite/{$subsite1ID}/edit", null, $this->adminLoggedInSession());
     $this->assertTrue(strpos($response2->getBody(), 'id="Form_EditForm_ID"') !== false, "Testing Form_EditForm_ID exists");
     $this->assertTrue(strpos($response2->getBody(), '<head') !== false, "Testing <head> exists");
 }
 /**
  * Get that visiting the field's URL returns the content of the field.
  * This capability is used by ajax
  */
 function testAjaxRefreshing()
 {
     $controller = new TableListFieldTest_TestController();
     $table = $controller->TestForm()->Fields()->First();
     $ajaxResponse = Director::test($table->Link())->getBody();
     // Check that the column headings have been rendered
     $this->assertRegExp('/<th[^>]*>\\s*Col A\\s*<\\/th>/', $ajaxResponse);
     $this->assertRegExp('/<th[^>]*>\\s*Col B\\s*<\\/th>/', $ajaxResponse);
     $this->assertRegExp('/<th[^>]*>\\s*Col C\\s*<\\/th>/', $ajaxResponse);
     $this->assertRegExp('/<th[^>]*>\\s*Col D\\s*<\\/th>/', $ajaxResponse);
     $this->assertRegExp('/<th[^>]*>\\s*Col E\\s*<\\/th>/', $ajaxResponse);
 }
 function testAllowedActions()
 {
     $response = Director::test("ControllerTest_SecuredController/methodaction");
     $this->assertEquals(200, $response->getStatusCode());
     $response = Director::test("ControllerTest_SecuredController/stringaction");
     $this->assertEquals(403, $response->getStatusCode());
     $response = Director::test("ControllerTest_SecuredController/adminonly");
     $this->assertEquals(403, $response->getStatusCode());
     // test that a controller without a specified allowed_actions allows actions through
     $response = Director::test('ControllerTest_UnsecuredController/stringaction');
     $this->assertEquals(200, $response->getStatusCode());
 }
 public function testOnsitePayment()
 {
     $stubGateway = $this->buildPaymentGatewayStub(true, 'test-' . $this->order->ID, false);
     Injector::inst()->registerService($this->stubGatewayFactory($stubGateway), 'Omnipay\\Common\\GatewayFactory');
     $ctrl = ModelAsController::controller_for($this->checkoutPage);
     $response = Director::test($ctrl->Link('ActionsForm'), array('action_dopayment' => true, 'OrderID' => $this->order->ID, 'PaymentMethod' => 'Dummy', 'type' => 'visa', 'name' => 'Tester Mc. Testerson', 'number' => '4242424242424242', 'expiryMonth' => 10, 'expiryYear' => date('Y') + 1, 'cvv' => 123), $this->session());
     // There should be a new payment
     $this->assertEquals(1, $this->order->Payments()->count());
     // The status of the payment should be Captured
     $this->assertEquals('Captured', $this->order->Payments()->first()->Status);
     // The response we get from submitting the form should be a redirect to the paid order
     $this->assertEquals($ctrl->Link('order/' . $this->order->ID), $response->getHeader('Location'));
 }
 /**
  * @inheritdoc
  *
  * @return array
  *
  * @throws SS_HTTPResponse_Exception
  */
 function check()
 {
     $response = Director::test($this->url);
     if ($response->getStatusCode() != 200) {
         return array(EnvironmentCheck::ERROR, sprintf('Error retrieving "%s" (Code: %d)', $this->url, $response->getStatusCode()));
     } else {
         if ($this->testString && strpos($response->getBody(), $this->testString) === false) {
             return array(EnvironmentCheck::WARNING, sprintf('Success retrieving "%s", but string "%s" not found', $this->url, $this->testString));
         } else {
             return array(EnvironmentCheck::OK, sprintf('Success retrieving "%s"', $this->url));
         }
     }
 }
 function export()
 {
     // specify custom baseurl for publishing to other webroot
     if (isset($_REQUEST['baseurl'])) {
         $base = $_REQUEST['baseurl'];
         if (substr($base, -1) != '/') {
             $base .= '/';
         }
         Director::setBaseURL($base);
     }
     // setup temporary folders
     $tmpBaseFolder = TEMP_FOLDER . '/static-export';
     $tmpFolder = project() ? "{$tmpBaseFolder}/" . project() : "{$tmpBaseFolder}/site";
     if (!file_exists($tmpFolder)) {
         Filesystem::makeFolder($tmpFolder);
     }
     $baseFolderName = basename($tmpFolder);
     // symlink /assets
     $f1 = ASSETS_PATH;
     $f2 = Director::baseFolder() . '/' . project();
     `cd {$tmpFolder}; ln -s {$f1}; ln -s {$f2}`;
     // iterate through all instances of SiteTree
     $pages = DataObject::get("SiteTree");
     foreach ($pages as $page) {
         $subfolder = "{$tmpFolder}/" . trim($page->RelativeLink(null, true), '/');
         $contentfile = "{$tmpFolder}/" . trim($page->RelativeLink(null, true), '/') . '/index.html';
         // Make the folder
         if (!file_exists($subfolder)) {
             Filesystem::makeFolder($subfolder);
         }
         // Run the page
         Requirements::clear();
         $link = Director::makeRelative($page->Link());
         $response = Director::test($link);
         // Write to file
         if ($fh = fopen($contentfile, 'w')) {
             fwrite($fh, $response->getBody());
             fclose($fh);
         }
     }
     // copy homepage (URLSegment: "home") to webroot
     copy("{$tmpFolder}/home/index.html", "{$tmpFolder}/index.html");
     // archive all generated files
     `cd {$tmpBaseFolder}; tar -czhf {$baseFolderName}.tar.gz {$baseFolderName}`;
     $archiveContent = file_get_contents("{$tmpBaseFolder}/{$baseFolderName}.tar.gz");
     // remove temporary files and folder
     Filesystem::removeFolder($tmpBaseFolder);
     // return as download to the client
     $response = SS_HTTPRequest::send_file($archiveContent, "{$baseFolderName}.tar.gz", 'application/x-tar-gz');
     echo $response->output();
 }
 /**
  * Test if the API gets a list of presentations
  */
 public function testItGetsAllPresentations()
 {
     $page = $this->objFromFixture('SummitVideoApp', 'App');
     $page->publish("Stage", "Live");
     $response = Director::test($page->Link('api/videos'));
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertNotEmpty($response->getBody());
     $data = Convert::json2array($response->getBody());
     $this->assertNull($data['summit']);
     $this->assertNull($data['speaker']);
     $this->assertCount(12, $data['results']);
     $this->assertEquals($this->objFromFixture('PresentationVideo', 'Video1')->ID, $data['results'][0]['id']);
     $this->assertEquals($this->objFromFixture('PresentationVideo', 'HighlightVideo1')->ID, $data['results'][3]['id']);
 }
 /**
  * Some static helpers for api specific requests and data tramsforming
  */
 static function request($method, $url, $data = null, $accessToken = null)
 {
     $body = null;
     if (is_array($data)) {
         $body = json_encode($data);
         if (!$body) {
             user_error('Could not encode json from $data');
         }
     }
     $headers = ["Content-Type" => "application/json"];
     if ($accessToken) {
         $headers['X-Accesstoken'] = $accessToken;
     }
     return Director::test($url, $postVars = null, $session = null, $httpMethod = $method, $body, $headers);
 }
 /**
  * Renders the contents of a silverstripe URL into a PDF
  *
  * @param String $url A relative URL that silverstripe can execute
  * @param String $outputTo
  */
 public function renderUrl($url, $outputTo = null, $outname = '')
 {
     if (strpos($url, '/') === 0) {
         // fix it
         $url = Director::makeRelative($url);
     }
     // convert the URL to content and 'test' the request, ensure the current session remains active
     $response = Director::test($url, null, new Session($_SESSION));
     if ($response->getStatusCode() == 200) {
         $content = $response->getBody();
         return $this->render($content, $outputTo, $outname);
     } else {
         throw new Exception("Failed rendering URL {$url}: " . $response->getStatusCode() . " - " . $response->getStatusDescription());
     }
 }
 public function updateNewsletterEmail(NewsletterEmail $email)
 {
     $newsletter = $email->Newsletter();
     if ($newsletter->ContentSource != 'page' || !$newsletter->SourcePageID) {
         return;
     }
     $page = $newsletter->SourcePage();
     $response = Director::test($page->RelativeLink());
     $body = $this->emogrify($response->getBody());
     $body = str_replace('xmlns="http://www.w3.org/1999/xhtml"', '', HTTP::absoluteURLs($body));
     $re = '/\\.src\\s*=' . str_replace('/', '\\/', Director::absoluteBaseURL()) . '/';
     $body = preg_replace($re, '.src =', $body);
     // undo the fudging that happens to keywords
     $body = preg_replace('/"[^"]*%7B%24(\\w+)%7D/', '"{\\$$1}', $body);
     $email->setBody(DBField::create('HTMLText', $body));
 }
 public function testPaymentIncomplete()
 {
     $this->processor->capture($this->data);
     //Test redirect to the gateway
     $response = Controller::curr()->getResponse();
     $gatewayURL = $this->processor->gateway->gatewayURL;
     $queryString = http_build_query(array('Amount' => $this->data['Amount'], 'Currency' => $this->data['Currency'], 'ReturnURL' => $this->processor->gateway->returnURL));
     $this->assertEquals($response->getHeader('Location'), '/dummy/external/pay?' . $queryString);
     //Test payment completion after redirect from gateway
     $queryString = http_build_query(array('Status' => 'Incomplete', 'ErrorMessage' => 'Awaiting Payment Confirmation', 'ErrorCode' => '54321'));
     Director::test($this->processor->gateway->returnURL . "?{$queryString}");
     $payment = $payment = Payment::get()->byID($this->processor->payment->ID);
     $this->assertEquals($payment->Status, Payment::INCOMPLETE);
     $error = $payment->Errors()->first();
     $this->assertEquals($error->ErrorMessage, 'Awaiting Payment Confirmation');
     $this->assertEquals($error->ErrorCode, '54321');
 }
 public function testDisabledOption()
 {
     // Enable module to error pages only
     Config::inst()->remove('Templater', 'enabled_for_pagetypes');
     Config::inst()->update('Templater', 'enabled_for_pagetypes', ['ErrorPage']);
     $page = $this->createPage('blue');
     $fields = $page->getCMSFields();
     $this->assertEmpty($fields->dataFieldByName('Theme'));
     $this->assertEmpty($fields->dataFieldByName('PageTemplate'));
     // Assert page content
     $response = Director::test(Director::makeRelative($page->Link()));
     $this->assertContains('Theme Blue page content', $response->getBody());
     $this->assertNotContains('I\'m in the Blue Theme', $response->getBody());
     // Enable module to all pages
     Config::inst()->remove('Templater', 'enabled_for_pagetypes');
     Config::inst()->update('Templater', 'enabled_for_pagetypes', 'all');
 }
Exemple #26
0
 function testDeleteAllCommentsOnPage()
 {
     $second = $this->objFromFixture('Page', 'second');
     $this->autoFollowRedirection = false;
     $this->logInAs('commentadmin');
     Director::test('second-page', null, $this->session());
     Director::test('PageComment/deleteallcomments?pageid=' . $second->ID, null, $this->session());
     Director::test('second-page', null, $this->session());
     $secondComments = DataObject::get('PageComment', '"ParentID" = ' . $second->ID);
     $this->assertNull($secondComments);
     $first = $this->objFromFixture('Page', 'first');
     $firstComments = DataObject::get('PageComment', '"ParentID" = ' . $first->ID);
     $this->assertNotNull($firstComments);
     $third = $this->objFromFixture('Page', 'third');
     $thirdComments = DataObject::get('PageComment', '"ParentID" = ' . $third->ID);
     $this->assertEquals($thirdComments->Count(), 3);
 }
Exemple #27
0
 function testBasicAuthEnabledWithoutPermission()
 {
     $origUser = @$_SERVER['PHP_AUTH_USER'];
     $origPw = @$_SERVER['PHP_AUTH_PW'];
     $_SERVER['PHP_AUTH_USER'] = '******';
     $_SERVER['PHP_AUTH_PW'] = 'wrongpassword';
     $response = Director::test('BasicAuthTest_ControllerSecuredWithoutPermission');
     $this->assertEquals(401, $response->getStatusCode(), 'Invalid users dont have access');
     $_SERVER['PHP_AUTH_USER'] = '******';
     $_SERVER['PHP_AUTH_PW'] = 'test';
     $response = Director::test('BasicAuthTest_ControllerSecuredWithoutPermission');
     $this->assertEquals(200, $response->getStatusCode(), 'All valid users have access');
     $_SERVER['PHP_AUTH_USER'] = '******';
     $_SERVER['PHP_AUTH_PW'] = 'test';
     $response = Director::test('BasicAuthTest_ControllerSecuredWithoutPermission');
     $this->assertEquals(200, $response->getStatusCode(), 'All valid users have access');
     $_SERVER['PHP_AUTH_USER'] = $origUser;
     $_SERVER['PHP_AUTH_PW'] = $origPw;
 }
	function test404ErrorPage() {
		$errorPage = DataObject::get_one('ErrorPage', "ErrorCode = '404'");

		/* We have an ErrorPage object to use */
		$this->assertTrue($errorPage instanceof ErrorPage);
		
		/* Test the URL of the error page out to get a response */
		$response = Director::test(Director::makeRelative($errorPage->Link()));
		
		/* We have an HTTPResponse object for the error page */
		$this->assertTrue($response instanceof HTTPResponse);
		
		/* We have body text from the error page */
		$this->assertTrue($response->getBody() != null);

		/* Status code of the HTTPResponse for error page is "404" */
		$this->assertTrue($response->getStatusCode() == '404');
		
		/* Status message of the HTTPResponse for error page is "Not Found" */
		$this->assertTrue($response->getStatusDescription() == 'Not Found');
	}
Exemple #29
0
 /**
  * Test publication of one of every page type
  */
 function testPublishOneOfEachKindOfPage()
 {
     return;
     $classes = ClassInfo::subclassesFor("SiteTree");
     array_shift($classes);
     unset($classes['GhostPage']);
     //Ghost Pages aren't used anymore
     foreach ($classes as $class) {
         $page = new $class();
         if ($class instanceof TestOnly) {
             continue;
         }
         $page->Title = "Test {$class} page";
         $page->write();
         $this->assertEquals("Test {$class} page", DB::query("SELECT Title FROM SiteTree WHERE ID = {$page->ID}")->value());
         $page->doPublish();
         $this->assertEquals("Test {$class} page", DB::query("SELECT Title FROM SiteTree_Live WHERE ID = {$page->ID}")->value());
         // Check that you can visit the page
         Director::test($page->Link());
     }
 }
Exemple #30
0
 /**
  * When an error page is published, create a static HTML page with its
  * content, so the page can be shown even when SilverStripe is not
  * functioning correctly before publishing this page normally.
  * @param string|int $fromStage Place to copy from. Can be either a stage name or a version number.
  * @param string $toStage Place to copy to. Must be a stage name.
  * @param boolean $createNewVersion Set this to true to create a new version number.  By default, the existing version number will be copied over.
  */
 function doPublish()
 {
     parent::doPublish();
     // Run the page
     $response = Director::test(Director::makeRelative($this->Link()));
     $errorContent = $response->getBody();
     // Check we have an assets base directory, creating if it we don't
     if (!file_exists(ASSETS_PATH)) {
         mkdir(ASSETS_PATH, 02775);
     }
     // if the page is published in a language other than default language,
     // write a specific language version of the HTML page
     $filePath = self::get_filepath_for_errorcode($this->ErrorCode, $this->Locale);
     if ($fh = fopen($filePath, "w")) {
         fwrite($fh, $errorContent);
         fclose($fh);
     } else {
         $fileErrorText = sprintf(_t("ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions."), $errorFile);
         FormResponse::status_message($fileErrorText, 'bad');
         FormResponse::respond();
         return;
     }
 }