function init()
 {
     parent::init();
     // somehow themed css gets mixed in, remove it
     $reqbe = Requirements::backend();
     foreach ($reqbe->get_css() as $file => $val) {
         if (preg_match('/^themes\\//', $file)) {
             Requirements::block($file);
         }
     }
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-form/jquery.form.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-livequery/jquery.livequery.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.core.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.widget.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.mouse.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.tabs.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.button.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.position.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.dialog.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.draggable.js');
     Requirements::css(THIRDPARTY_DIR . '/jquery-ui-themes/base/jquery.ui.core.css');
     Requirements::css(THIRDPARTY_DIR . '/jquery-ui-themes/base/jquery.ui.dialog.css');
     Requirements::css(THIRDPARTY_DIR . '/jquery-ui-themes/base/jquery.ui.theme.css');
     Requirements::css(THIRDPARTY_DIR . '/jquery-ui-themes/base/jquery.ui.tabs.css');
     Requirements::clear('jsparty/prototype.js');
     Requirements::javascript(SAPPHIRE_DIR . "/javascript/i18n.js");
     Requirements::add_i18n_javascript('dbplumber/javascript/lang');
     Requirements::javascript("dbplumber/javascript/DatabaseBrowser.js");
     Requirements::javascript("dbplumber/thirdparty/jquery.event.drag-1.4.js");
     Requirements::javascript("dbplumber/thirdparty/jquery.kiketable.colsizable-1.1.js");
     Requirements::javascript("dbplumber/thirdparty/jquery.textarea-expander.js");
     Requirements::css("dbplumber/thirdparty/jquery.kiketable.colsizable-1.1.css");
     Requirements::css("dbplumber/css/DatabaseBrowser_left.css");
     Requirements::css("dbplumber/css/DatabaseBrowser_right.css");
 }
 protected function jQueryAlreadyIncluded()
 {
     foreach (Requirements::backend()->get_javascript() as $script) {
         if (preg_match('/jquery/i', $script)) {
             return true;
         }
     }
     return false;
 }
 public function onBeforeInit()
 {
     if (!is_subclass_of(Controller::curr(), "LeftAndMain")) {
         $this->backend = Requirements::backend();
         $jsMin = Director::isDev() ? "" : ".min";
         $toBlock = array(FRAMEWORK_DIR . "/thirdparty/jquery/jquery.js", FRAMEWORK_DIR . "/thirdparty/jquery/jquery.min.js");
         $toPrepend = array("silverstripe-jquery/thirdparty/jquery/jquery" . $jsMin . ".js", "silverstripe-jquery/thirdparty/jquery-migrate/jquery-migrate" . $jsMin . ".js");
         $this->mungeRequirementsJs($toBlock, $toPrepend);
     }
 }
Ejemplo n.º 4
0
	function setUp() {
		// Mark test as being run
		$this->originalIsRunningTest = self::$is_running_test;
		self::$is_running_test = true;
		
		// Remove password validation
		$this->originalMemberPasswordValidator = Member::password_validator();
		$this->originalRequirements = Requirements::backend();
		Member::set_password_validator(null);
		Cookie::set_report_errors(false);

		$className = get_class($this);
		$fixtureFile = eval("return {$className}::\$fixture_file;");
		
		// Set up fixture
		if($fixtureFile) {
			if(substr(DB::getConn()->currentDatabase(),0,5) != 'tmpdb') {
				//echo "Re-creating temp database... ";
				self::create_temp_db();
				//echo "done.\n";
			}

			// This code is a bit misplaced; we want some way of the whole session being reinitialised...
			Versioned::reading_stage(null);

			singleton('DataObject')->flushCache();

			$dbadmin = new DatabaseAdmin();
			$dbadmin->clearAllData();
			
			// We have to disable validation while we import the fixtures, as the order in
			// which they are imported doesnt guarantee valid relations until after the
			// import is complete.
			$validationenabled = DataObject::get_validation_enabled();
			DataObject::set_validation_enabled(false);
			$this->fixture = new YamlFixture($fixtureFile);
			$this->fixture->saveIntoDatabase();
			DataObject::set_validation_enabled($validationenabled);
		}
		
		// Set up email
		$this->originalMailer = Email::mailer();
		$this->mailer = new TestMailer();
		Email::set_mailer($this->mailer);
	}
Ejemplo n.º 5
0
 function testExternalUrls()
 {
     $backend = Requirements::backend();
     $backend->set_combined_files_enabled(true);
     $backend->js('http://www.mydomain.com/test.js');
     $backend->js('https://www.mysecuredomain.com/test2.js');
     $backend->css('http://www.mydomain.com/test.css');
     $backend->css('https://www.mysecuredomain.com/test2.css');
     $html = $backend->render();
     $this->assertContains('http://www.mydomain.com/test.js', $html, 'Load external javascript URL');
     $this->assertContains('https://www.mysecuredomain.com/test2.js', $html, 'Load external secure javascript URL');
     $this->assertContains('http://www.mydomain.com/test.css', $html, 'Load external CSS URL');
     $this->assertContains('https://www.mysecuredomain.com/test2.css', $html, 'Load external secure CSS URL');
     // This should replace test.css above
     // @todo move to seperate test
     $backend->css('https://www.anything.com/test.css');
     $html = $backend->render();
     $this->assertContains('https://www.anything.com/test.css', $html, 'Load external CSS URL');
     $this->assertNotContains('https://www.mydomain.com/test.css', $html, 'Load external CSS URL');
 }
Ejemplo n.º 6
0
 public function testRequirementsCombine()
 {
     $oldBackend = Requirements::backend();
     $testBackend = new Requirements_Backend();
     Requirements::set_backend($testBackend);
     $combinedTestFilePath = BASE_PATH . '/' . $testBackend->getCombinedFilesFolder() . '/testRequirementsCombine.js';
     $jsFile = FRAMEWORK_DIR . '/tests/view/themes/javascript/bad.js';
     $jsFileContents = file_get_contents(BASE_PATH . '/' . $jsFile);
     Requirements::combine_files('testRequirementsCombine.js', array($jsFile));
     require_once 'thirdparty/jsmin/jsmin.php';
     // first make sure that our test js file causes an exception to be thrown
     try {
         $content = JSMin::minify($content);
         Requirements::set_backend($oldBackend);
         $this->fail('JSMin did not throw exception on minify bad file: ');
     } catch (Exception $e) {
         // exception thrown... good
     }
     // secondly, make sure that requirements combine throws the correct warning, and only that warning
     @unlink($combinedTestFilePath);
     try {
         Requirements::process_combined_files();
     } catch (PHPUnit_Framework_Error_Warning $e) {
         if (strstr($e->getMessage(), 'Failed to minify') === false) {
             Requirements::set_backend($oldBackend);
             $this->fail('Requirements::process_combined_files raised a warning, which is good, but this is not the expected warning ("Failed to minify..."): ' . $e);
         }
     } catch (Exception $e) {
         Requirements::set_backend($oldBackend);
         $this->fail('Requirements::process_combined_files did not catch exception caused by minifying bad js file: ' . $e);
     }
     // and make sure the combined content matches the input content, i.e. no loss of functionality
     if (!file_exists($combinedTestFilePath)) {
         Requirements::set_backend($oldBackend);
         $this->fail('No combined file was created at expected path: ' . $combinedTestFilePath);
     }
     $combinedTestFileContents = file_get_contents($combinedTestFilePath);
     $this->assertContains($jsFileContents, $combinedTestFileContents);
     // reset
     Requirements::set_backend($oldBackend);
 }
Ejemplo n.º 7
0
 public function testConditionalTemplateRequire()
 {
     $basePath = $this->getCurrentRelativePath();
     // we're asserting "framework", so set the relative path accordingly in case FRAMEWORK_DIR was changed
     // to something else
     $basePath = 'framework' . substr($basePath, strlen(FRAMEWORK_DIR));
     $backend = new Requirements_Backend();
     $holder = Requirements::backend();
     Requirements::set_backend($backend);
     $data = new ArrayData(array('FailTest' => true));
     $data->renderWith('RequirementsTest_Conditionals');
     $this->assertFileIncluded($backend, 'css', $basePath . '/RequirementsTest_a.css');
     $this->assertFileIncluded($backend, 'js', array($basePath . '/RequirementsTest_b.js', $basePath . '/RequirementsTest_c.js'));
     $this->assertFileNotIncluded($backend, 'js', $basePath . '/RequirementsTest_a.js');
     $this->assertFileNotIncluded($backend, 'css', array($basePath . '/RequirementsTest_b.css', $basePath . '/RequirementsTest_c.css'));
     $backend->clear();
     $data = new ArrayData(array('FailTest' => false));
     $data->renderWith('RequirementsTest_Conditionals');
     $this->assertFileNotIncluded($backend, 'css', $basePath . '/RequirementsTest_a.css');
     $this->assertFileNotIncluded($backend, 'js', array($basePath . '/RequirementsTest_b.js', $basePath . '/RequirementsTest_c.js'));
     $this->assertFileIncluded($backend, 'js', $basePath . '/RequirementsTest_a.js');
     $this->assertFileIncluded($backend, 'css', array($basePath . '/RequirementsTest_b.css', $basePath . '/RequirementsTest_c.css'));
     Requirements::set_backend($holder);
 }
 public static function process_queue_invoke($newsletterID)
 {
     $lockFile = Director::getAbsFile(Requirements::backend()->getCombinedFilesFolder() . '/_newsletter_send_cache.lock');
     if (!file_exists($lockFile) || (int) file_get_contents($lockFile) < time() - 180) {
         file_put_contents($lockFile, time());
         $nsc = NewsletterSendController::inst();
         $nsc->processQueue($newsletterID, $lockFile);
     }
 }
Ejemplo n.º 9
0
 public static function renderDebugBar()
 {
     if (!self::$renderer) {
         return;
     }
     // Requirements may have been cleared (CMS iframes...) or not set (Security...)
     $js = Requirements::backend()->get_javascript();
     if (!in_array('debugbar/assets/debugbar.js', $js)) {
         return;
     }
     $initialize = true;
     if (Director::is_ajax()) {
         $initialize = false;
     }
     $script = self::$renderer->render($initialize);
     return $script;
 }
Ejemplo n.º 10
0
 /**
  * Test a URL request, returning a response object.
  * 
  * This method is the counterpart of Director::direct() that is used in functional testing.  It will execute the
  * URL given, and return the result as an SS_HTTPResponse object.
  * 
  * @param string $url The URL to visit
  * @param array $postVars The $_POST & $_FILES variables
  * @param Session $session The {@link Session} object representing the current session.  By passing the same
  *                         object to multiple  calls of Director::test(), you can simulate a persisted session.
  * @param string $httpMethod The HTTP method, such as GET or POST.  It will default to POST if postVars is set,
  *                           GET otherwise. Overwritten by $postVars['_method'] if present.
  * @param string $body The HTTP body
  * @param array $headers HTTP headers with key-value pairs
  * @param array $cookies to populate $_COOKIE
  * @param HTTP_Request $request The {@see HTTP_Request} object generated as a part of this request
  * @return SS_HTTPResponse
  * 
  * @uses getControllerForURL() The rule-lookup logic is handled by this.
  * @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call.
  */
 public static function test($url, $postVars = null, $session = null, $httpMethod = null, $body = null, $headers = null, $cookies = null, &$request = null)
 {
     Config::nest();
     // These are needed so that calling Director::test() doesnt muck with whoever is calling it.
     // Really, it's some inappropriate coupling and should be resolved by making less use of statics
     $oldStage = Versioned::current_stage();
     $getVars = array();
     if (!$httpMethod) {
         $httpMethod = $postVars || is_array($postVars) ? "POST" : "GET";
     }
     if (!$session) {
         $session = new Session(null);
     }
     // Back up the current values of the superglobals
     $existingRequestVars = isset($_REQUEST) ? $_REQUEST : array();
     $existingGetVars = isset($_GET) ? $_GET : array();
     $existingPostVars = isset($_POST) ? $_POST : array();
     $existingSessionVars = isset($_SESSION) ? $_SESSION : array();
     $existingCookies = isset($_COOKIE) ? $_COOKIE : array();
     $existingServer = isset($_SERVER) ? $_SERVER : array();
     $existingRequirementsBackend = Requirements::backend();
     Config::inst()->update('Cookie', 'report_errors', false);
     Requirements::set_backend(new Requirements_Backend());
     // Handle absolute URLs
     if (@parse_url($url, PHP_URL_HOST) != '') {
         $bits = parse_url($url);
         $_SERVER['HTTP_HOST'] = $bits['host'];
         $url = Director::makeRelative($url);
     }
     $urlWithQuerystring = $url;
     if (strpos($url, '?') !== false) {
         list($url, $getVarsEncoded) = explode('?', $url, 2);
         parse_str($getVarsEncoded, $getVars);
     }
     // Replace the superglobals with appropriate test values
     $_REQUEST = ArrayLib::array_merge_recursive((array) $getVars, (array) $postVars);
     $_GET = (array) $getVars;
     $_POST = (array) $postVars;
     $_SESSION = $session ? $session->inst_getAll() : array();
     $_COOKIE = (array) $cookies;
     $_SERVER['REQUEST_URI'] = Director::baseURL() . $urlWithQuerystring;
     $request = new SS_HTTPRequest($httpMethod, $url, $getVars, $postVars, $body);
     if ($headers) {
         foreach ($headers as $k => $v) {
             $request->addHeader($k, $v);
         }
     }
     // Pre-request filtering
     // @see issue #2517
     $model = DataModel::inst();
     $output = Injector::inst()->get('RequestProcessor')->preRequest($request, $session, $model);
     if ($output === false) {
         // @TODO Need to NOT proceed with the request in an elegant manner
         throw new SS_HTTPResponse_Exception(_t('Director.INVALID_REQUEST', 'Invalid request'), 400);
     }
     // TODO: Pass in the DataModel
     $result = Director::handleRequest($request, $session, $model);
     // Ensure that the result is an SS_HTTPResponse object
     if (is_string($result)) {
         if (substr($result, 0, 9) == 'redirect:') {
             $response = new SS_HTTPResponse();
             $response->redirect(substr($result, 9));
             $result = $response;
         } else {
             $result = new SS_HTTPResponse($result);
         }
     }
     $output = Injector::inst()->get('RequestProcessor')->postRequest($request, $result, $model);
     if ($output === false) {
         throw new SS_HTTPResponse_Exception("Invalid response");
     }
     // Restore the superglobals
     $_REQUEST = $existingRequestVars;
     $_GET = $existingGetVars;
     $_POST = $existingPostVars;
     $_SESSION = $existingSessionVars;
     $_COOKIE = $existingCookies;
     $_SERVER = $existingServer;
     Requirements::set_backend($existingRequirementsBackend);
     // These are needed so that calling Director::test() doesnt muck with whoever is calling it.
     // Really, it's some inappropriate coupling and should be resolved by making less use of statics
     Versioned::reading_stage($oldStage);
     Config::unnest();
     return $result;
 }
Ejemplo n.º 11
0
 /**
  * Test a URL request, returning a response object. This method is the counterpart of
  * Director::direct() that is used in functional testing. It will execute the URL given, and
  * return the result as an SS_HTTPResponse object.
  *
  * @uses getControllerForURL() The rule-lookup logic is handled by this.
  * @uses Controller::run() Handles the page logic for a Director::direct() call.
  *
  * @param string $url The URL to visit.
  * @param array $postVars The $_POST & $_FILES variables.
  * @param array|Session $session The {@link Session} object representing the current session.
  * By passing the same object to multiple  calls of Director::test(), you can simulate a persisted
  * session.
  * @param string $httpMethod The HTTP method, such as GET or POST.  It will default to POST if
  * postVars is set, GET otherwise. Overwritten by $postVars['_method'] if present.
  * @param string $body The HTTP body.
  * @param array $headers HTTP headers with key-value pairs.
  * @param array|Cookie_Backend $cookies to populate $_COOKIE.
  * @param HTTP_Request $request The {@see HTTP_Request} object generated as a part of this request.
  *
  * @return SS_HTTPResponse
  *
  * @throws SS_HTTPResponse_Exception
  */
 public static function test($url, $postVars = null, $session = array(), $httpMethod = null, $body = null, $headers = array(), $cookies = array(), &$request = null)
 {
     Config::nest();
     Injector::nest();
     // These are needed so that calling Director::test() does not muck with whoever is calling it.
     // Really, it's some inappropriate coupling and should be resolved by making less use of statics.
     $oldReadingMode = Versioned::get_reading_mode();
     $getVars = array();
     if (!$httpMethod) {
         $httpMethod = $postVars || is_array($postVars) ? "POST" : "GET";
     }
     if (!$session) {
         $session = Injector::inst()->create('Session', array());
     }
     $cookieJar = $cookies instanceof Cookie_Backend ? $cookies : Injector::inst()->createWithArgs('Cookie_Backend', array($cookies ?: array()));
     // Back up the current values of the superglobals
     $existingRequestVars = isset($_REQUEST) ? $_REQUEST : array();
     $existingGetVars = isset($_GET) ? $_GET : array();
     $existingPostVars = isset($_POST) ? $_POST : array();
     $existingSessionVars = isset($_SESSION) ? $_SESSION : array();
     $existingCookies = isset($_COOKIE) ? $_COOKIE : array();
     $existingServer = isset($_SERVER) ? $_SERVER : array();
     $existingRequirementsBackend = Requirements::backend();
     Config::inst()->update('Cookie', 'report_errors', false);
     Requirements::set_backend(Injector::inst()->create('Requirements_Backend'));
     // Set callback to invoke prior to return
     $onCleanup = function () use($existingRequestVars, $existingGetVars, $existingPostVars, $existingSessionVars, $existingCookies, $existingServer, $existingRequirementsBackend, $oldReadingMode) {
         // Restore the super globals
         $_REQUEST = $existingRequestVars;
         $_GET = $existingGetVars;
         $_POST = $existingPostVars;
         $_SESSION = $existingSessionVars;
         $_COOKIE = $existingCookies;
         $_SERVER = $existingServer;
         Requirements::set_backend($existingRequirementsBackend);
         // These are needed so that calling Director::test() does not muck with whoever is calling it.
         // Really, it's some inappropriate coupling and should be resolved by making less use of statics
         Versioned::set_reading_mode($oldReadingMode);
         Injector::unnest();
         // Restore old CookieJar, etc
         Config::unnest();
     };
     if (strpos($url, '#') !== false) {
         $url = substr($url, 0, strpos($url, '#'));
     }
     // Handle absolute URLs
     if (parse_url($url, PHP_URL_HOST)) {
         $bits = parse_url($url);
         // If a port is mentioned in the absolute URL, be sure to add that into the HTTP host
         if (isset($bits['port'])) {
             $_SERVER['HTTP_HOST'] = $bits['host'] . ':' . $bits['port'];
         } else {
             $_SERVER['HTTP_HOST'] = $bits['host'];
         }
     }
     // Ensure URL is properly made relative.
     // Example: url passed is "/ss31/my-page" (prefixed with BASE_URL), this should be changed to "my-page"
     $url = self::makeRelative($url);
     $urlWithQuerystring = $url;
     if (strpos($url, '?') !== false) {
         list($url, $getVarsEncoded) = explode('?', $url, 2);
         parse_str($getVarsEncoded, $getVars);
     }
     // Replace the super globals with appropriate test values
     $_REQUEST = ArrayLib::array_merge_recursive((array) $getVars, (array) $postVars);
     $_GET = (array) $getVars;
     $_POST = (array) $postVars;
     $_SESSION = $session ? $session->inst_getAll() : array();
     $_COOKIE = $cookieJar->getAll(false);
     Injector::inst()->registerService($cookieJar, 'Cookie_Backend');
     $_SERVER['REQUEST_URI'] = Director::baseURL() . $urlWithQuerystring;
     $request = new SS_HTTPRequest($httpMethod, $url, $getVars, $postVars, $body);
     if ($headers) {
         foreach ($headers as $k => $v) {
             $request->addHeader($k, $v);
         }
     }
     // Pre-request filtering
     // @see issue #2517
     $model = DataModel::inst();
     $output = Injector::inst()->get('RequestProcessor')->preRequest($request, $session, $model);
     if ($output === false) {
         $onCleanup();
         throw new SS_HTTPResponse_Exception(_t('Director.INVALID_REQUEST', 'Invalid request'), 400);
     }
     // TODO: Pass in the DataModel
     $result = Director::handleRequest($request, $session, $model);
     // Ensure that the result is an SS_HTTPResponse object
     if (is_string($result)) {
         if (substr($result, 0, 9) == 'redirect:') {
             $response = new SS_HTTPResponse();
             $response->redirect(substr($result, 9));
             $result = $response;
         } else {
             $result = new SS_HTTPResponse($result);
         }
     }
     $output = Injector::inst()->get('RequestProcessor')->postRequest($request, $result, $model);
     if ($output === false) {
         $onCleanup();
         throw new SS_HTTPResponse_Exception("Invalid response");
     }
     // Return valid response
     $onCleanup();
     return $result;
 }
 function setUp()
 {
     // Mark test as being run
     $this->originalIsRunningTest = self::$is_running_test;
     self::$is_running_test = true;
     // i18n needs to be set to the defaults or tests fail
     i18n::set_locale(i18n::default_locale());
     i18n::set_date_format(null);
     i18n::set_time_format(null);
     // Remove password validation
     $this->originalMemberPasswordValidator = Member::password_validator();
     $this->originalRequirements = Requirements::backend();
     Member::set_password_validator(null);
     Cookie::set_report_errors(false);
     RootURLController::reset();
     Translatable::reset();
     Versioned::reset();
     DataObject::reset();
     SiteTree::reset();
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(new Session(array()));
     }
     $this->originalTheme = SSViewer::current_theme();
     // Save nested_urls state, so we can restore it later
     $this->originalNestedURLsState = SiteTree::nested_urls();
     $className = get_class($this);
     $fixtureFile = eval("return {$className}::\$fixture_file;");
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     // Set up fixture
     if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) {
         if (substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) {
             //echo "Re-creating temp database... ";
             self::create_temp_db();
             //echo "done.\n";
         }
         singleton('DataObject')->flushCache();
         self::empty_temp_db();
         foreach ($this->requireDefaultRecordsFrom as $className) {
             $instance = singleton($className);
             if (method_exists($instance, 'requireDefaultRecords')) {
                 $instance->requireDefaultRecords();
             }
             if (method_exists($instance, 'augmentDefaultRecords')) {
                 $instance->augmentDefaultRecords();
             }
         }
         if ($fixtureFile) {
             $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile);
             $i = 0;
             foreach ($fixtureFiles as $fixtureFilePath) {
                 $fixture = new YamlFixture($fixtureFilePath);
                 $fixture->saveIntoDatabase();
                 $this->fixtures[] = $fixture;
                 // backwards compatibility: Load first fixture into $this->fixture
                 if ($i == 0) {
                     $this->fixture = $fixture;
                 }
                 $i++;
             }
         }
         $this->logInWithPermission("ADMIN");
     }
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Email::set_mailer($this->mailer);
     Email::send_all_emails_to(null);
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
 }
Ejemplo n.º 13
0
 /**
  * Test a URL request, returning a response object.
  * 
  * This method is the counterpart of Director::direct() that is used in functional testing.  It will execute the URL given,
  * 
  * @param string $url The URL to visit
  * @param array $postVars The $_POST & $_FILES variables
  * @param Session $session The {@link Session} object representing the current session.  By passing the same object to multiple
  * calls of Director::test(), you can simulate a persisted session.
  * @param string $httpMethod The HTTP method, such as GET or POST.  It will default to POST if postVars is set, GET otherwise.
  *  Overwritten by $postVars['_method'] if present.
  * @param string $body The HTTP body
  * @param array $headers HTTP headers with key-value pairs
  * @param array $cookies to populate $_COOKIE
  * @return SS_HTTPResponse
  * 
  * @uses getControllerForURL() The rule-lookup logic is handled by this.
  * @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call.
  */
 static function test($url, $postVars = null, $session = null, $httpMethod = null, $body = null, $headers = null, $cookies = null)
 {
     // These are needed so that calling Director::test() doesnt muck with whoever is calling it.
     // Really, it's some inappropriate coupling and should be resolved by making less use of statics
     $oldStage = Versioned::current_stage();
     $getVars = array();
     if (!$httpMethod) {
         $httpMethod = $postVars || is_array($postVars) ? "POST" : "GET";
     }
     if (!$session) {
         $session = new Session(null);
     }
     // Back up the current values of the superglobals
     $existingRequestVars = isset($_REQUEST) ? $_REQUEST : array();
     $existingGetVars = isset($_GET) ? $_GET : array();
     $existingPostVars = isset($_POST) ? $_POST : array();
     $existingSessionVars = isset($_SESSION) ? $_SESSION : array();
     $existingCookies = isset($_COOKIE) ? $_COOKIE : array();
     $existingServer = isset($_SERVER) ? $_SERVER : array();
     $existingCookieReportErrors = Cookie::report_errors();
     $existingRequirementsBackend = Requirements::backend();
     Cookie::set_report_errors(false);
     Requirements::set_backend(new Requirements_Backend());
     // Handle absolute URLs
     if (@parse_url($url, PHP_URL_HOST) != '') {
         $bits = parse_url($url);
         $_SERVER['HTTP_HOST'] = $bits['host'];
         $url = Director::makeRelative($url);
     }
     $urlWithQuerystring = $url;
     if (strpos($url, '?') !== false) {
         list($url, $getVarsEncoded) = explode('?', $url, 2);
         parse_str($getVarsEncoded, $getVars);
     }
     // Replace the superglobals with appropriate test values
     $_REQUEST = array_merge((array) $getVars, (array) $postVars);
     $_GET = (array) $getVars;
     $_POST = (array) $postVars;
     $_SESSION = $session ? $session->inst_getAll() : array();
     $_COOKIE = (array) $cookies;
     $_SERVER['REQUEST_URI'] = Director::baseURL() . $urlWithQuerystring;
     $req = new SS_HTTPRequest($httpMethod, $url, $getVars, $postVars, $body);
     if ($headers) {
         foreach ($headers as $k => $v) {
             $req->addHeader($k, $v);
         }
     }
     $result = Director::handleRequest($req, $session);
     // Restore the superglobals
     $_REQUEST = $existingRequestVars;
     $_GET = $existingGetVars;
     $_POST = $existingPostVars;
     $_SESSION = $existingSessionVars;
     $_COOKIE = $existingCookies;
     $_SERVER = $existingServer;
     Cookie::set_report_errors($existingCookieReportErrors);
     Requirements::set_backend($existingRequirementsBackend);
     // These are needed so that calling Director::test() doesnt muck with whoever is calling it.
     // Really, it's some inappropriate coupling and should be resolved by making less use of statics
     Versioned::reading_stage($oldStage);
     return $result;
 }
 function testConditionalTemplateRequire()
 {
     $backend = new RequirementsTest_Backend();
     $holder = Requirements::backend();
     Requirements::set_backend($backend);
     $data = new ArrayData(array('FailTest' => true));
     $data->renderWith('RequirementsTest_Conditionals');
     $backend->assertFileIncluded('css', 'sapphire/tests/forms/RequirementsTest_a.css');
     $backend->assertFileIncluded('js', array('sapphire/tests/forms/RequirementsTest_b.js', 'sapphire/tests/forms/RequirementsTest_c.js'));
     $backend->assertFileNotIncluded('js', 'sapphire/tests/forms/RequirementsTest_a.js');
     $backend->assertFileNotIncluded('css', array('sapphire/tests/forms/RequirementsTest_b.css', 'sapphire/tests/forms/RequirementsTest_c.css'));
     $backend->clear();
     $data = new ArrayData(array('FailTest' => false));
     $data->renderWith('RequirementsTest_Conditionals');
     $backend->assertFileNotIncluded('css', 'sapphire/tests/forms/RequirementsTest_a.css');
     $backend->assertFileNotIncluded('js', array('sapphire/tests/forms/RequirementsTest_b.js', 'sapphire/tests/forms/RequirementsTest_c.js'));
     $backend->assertFileIncluded('js', 'sapphire/tests/forms/RequirementsTest_a.js');
     $backend->assertFileIncluded('css', array('sapphire/tests/forms/RequirementsTest_b.css', 'sapphire/tests/forms/RequirementsTest_c.css'));
     Requirements::set_backend($holder);
 }
 public function testRequirements()
 {
     $requirements = $this->getMock("Requirements_Backend", array("javascript", "css"));
     $jsFile = FRAMEWORK_DIR . '/tests/forms/a.js';
     $cssFile = FRAMEWORK_DIR . '/tests/forms/a.js';
     $requirements->expects($this->once())->method('javascript')->with($jsFile);
     $requirements->expects($this->once())->method('css')->with($cssFile);
     $origReq = Requirements::backend();
     Requirements::set_backend($requirements);
     $template = $this->render("<% require javascript({$jsFile}) %>\n\t\t<% require css({$cssFile}) %>");
     Requirements::set_backend($origReq);
     $this->assertFalse((bool) trim($template), "Should be no content in this return.");
 }
Ejemplo n.º 16
0
 /**
  * Set this store as the new asset backend
  *
  * @param string $basedir Basedir to store assets, which will be placed beneath 'assets' folder
  */
 public static function activate($basedir)
 {
     // Assign this as the new store
     $adapter = new AssetAdapter(ASSETS_PATH . '/' . $basedir);
     $filesystem = new Filesystem($adapter);
     $filesystem->addPlugin(new FlysystemUrlPlugin());
     $backend = new AssetStoreTest_SpyStore();
     $backend->setFilesystem($filesystem);
     Injector::inst()->registerService($backend, 'AssetStore');
     // Assign flysystem backend to generated asset handler at the same time
     $generated = new FlysystemGeneratedAssetHandler();
     $generated->setFilesystem($filesystem);
     Injector::inst()->registerService($generated, 'GeneratedAssetHandler');
     Requirements::backend()->setAssetHandler($generated);
     // Disable legacy and set defaults
     Config::inst()->remove(get_class(new FlysystemAssetStore()), 'legacy_filenames');
     Config::inst()->update('Director', 'alternate_base_url', '/');
     DBFile::config()->force_resample = false;
     File::config()->force_resample = false;
     self::reset();
     self::$basedir = $basedir;
     // Ensure basedir exists
     SS_Filesystem::makeFolder(self::base_path());
 }
Ejemplo n.º 17
0
 function setUp()
 {
     // We cannot run the tests on this abstract class.
     if (get_class($this) == "SapphireTest") {
         $this->skipTest = true;
     }
     if ($this->skipTest) {
         $this->markTestSkipped(sprintf('Skipping %s ', get_class($this)));
         return;
     }
     // Mark test as being run
     $this->originalIsRunningTest = self::$is_running_test;
     self::$is_running_test = true;
     // i18n needs to be set to the defaults or tests fail
     i18n::set_locale(i18n::default_locale());
     i18n::set_date_format(null);
     i18n::set_time_format(null);
     // Remove password validation
     $this->originalMemberPasswordValidator = Member::password_validator();
     $this->originalRequirements = Requirements::backend();
     Member::set_password_validator(null);
     Cookie::set_report_errors(false);
     if (class_exists('RootURLController')) {
         RootURLController::reset();
     }
     if (class_exists('Translatable')) {
         Translatable::reset();
     }
     Versioned::reset();
     DataObject::reset();
     if (class_exists('SiteTree')) {
         SiteTree::reset();
     }
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(new Session(array()));
     }
     $this->originalTheme = SSViewer::current_theme();
     if (class_exists('SiteTree')) {
         // Save nested_urls state, so we can restore it later
         $this->originalNestedURLsState = SiteTree::nested_urls();
     }
     $className = get_class($this);
     $fixtureFile = eval("return {$className}::\$fixture_file;");
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     // Todo: this could be a special test model
     $this->model = DataModel::inst();
     // Set up fixture
     if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) {
         if (substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) {
             //echo "Re-creating temp database... ";
             self::create_temp_db();
             //echo "done.\n";
         }
         singleton('DataObject')->flushCache();
         self::empty_temp_db();
         foreach ($this->requireDefaultRecordsFrom as $className) {
             $instance = singleton($className);
             if (method_exists($instance, 'requireDefaultRecords')) {
                 $instance->requireDefaultRecords();
             }
             if (method_exists($instance, 'augmentDefaultRecords')) {
                 $instance->augmentDefaultRecords();
             }
         }
         if ($fixtureFile) {
             $pathForClass = $this->getCurrentAbsolutePath();
             $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile);
             $i = 0;
             foreach ($fixtureFiles as $fixtureFilePath) {
                 // Support fixture paths relative to the test class, rather than relative to webroot
                 // String checking is faster than file_exists() calls.
                 $isRelativeToFile = strpos('/', $fixtureFilePath) === false || preg_match('/^\\.\\./', $fixtureFilePath);
                 if ($isRelativeToFile) {
                     $resolvedPath = realpath($pathForClass . '/' . $fixtureFilePath);
                     if ($resolvedPath) {
                         $fixtureFilePath = $resolvedPath;
                     }
                 }
                 $fixture = new YamlFixture($fixtureFilePath);
                 $fixture->saveIntoDatabase($this->model);
                 $this->fixtures[] = $fixture;
                 // backwards compatibility: Load first fixture into $this->fixture
                 if ($i == 0) {
                     $this->fixture = $fixture;
                 }
                 $i++;
             }
         }
         $this->logInWithPermission("ADMIN");
     }
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Email::set_mailer($this->mailer);
     Email::send_all_emails_to(null);
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
 }
 public function setUp()
 {
     // We cannot run the tests on this abstract class.
     if (get_class($this) == "SapphireTest") {
         $this->skipTest = true;
     }
     if ($this->skipTest) {
         $this->markTestSkipped(sprintf('Skipping %s ', get_class($this)));
         return;
     }
     // Mark test as being run
     $this->originalIsRunningTest = self::$is_running_test;
     self::$is_running_test = true;
     // i18n needs to be set to the defaults or tests fail
     i18n::set_locale(i18n::default_locale());
     i18n::config()->date_format = null;
     i18n::config()->time_format = null;
     // Set default timezone consistently to avoid NZ-specific dependencies
     date_default_timezone_set('UTC');
     // Remove password validation
     $this->originalMemberPasswordValidator = Member::password_validator();
     $this->originalRequirements = Requirements::backend();
     Member::set_password_validator(null);
     Config::inst()->update('Cookie', 'report_errors', false);
     if (class_exists('RootURLController')) {
         RootURLController::reset();
     }
     if (class_exists('Translatable')) {
         Translatable::reset();
     }
     Versioned::reset();
     DataObject::reset();
     if (class_exists('SiteTree')) {
         SiteTree::reset();
     }
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(Injector::inst()->create('Session', array()));
     }
     Security::$database_is_ready = null;
     // Add controller-name auto-routing
     Config::inst()->update('Director', 'rules', array('$Controller//$Action/$ID/$OtherID' => '*'));
     $fixtureFile = static::get_fixture_file();
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Email::set_mailer($this->mailer);
     Config::inst()->remove('Email', 'send_all_emails_to');
     // Todo: this could be a special test model
     $this->model = DataModel::inst();
     // Set up fixture
     if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) {
         if (substr(DB::get_conn()->getSelectedDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) {
             //echo "Re-creating temp database... ";
             self::create_temp_db();
             //echo "done.\n";
         }
         singleton('DataObject')->flushCache();
         self::empty_temp_db();
         foreach ($this->requireDefaultRecordsFrom as $className) {
             $instance = singleton($className);
             if (method_exists($instance, 'requireDefaultRecords')) {
                 $instance->requireDefaultRecords();
             }
             if (method_exists($instance, 'augmentDefaultRecords')) {
                 $instance->augmentDefaultRecords();
             }
         }
         if ($fixtureFile) {
             $pathForClass = $this->getCurrentAbsolutePath();
             $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile);
             $i = 0;
             foreach ($fixtureFiles as $fixtureFilePath) {
                 // Support fixture paths relative to the test class, rather than relative to webroot
                 // String checking is faster than file_exists() calls.
                 $isRelativeToFile = strpos('/', $fixtureFilePath) === false || preg_match('/^\\.\\./', $fixtureFilePath);
                 if ($isRelativeToFile) {
                     $resolvedPath = realpath($pathForClass . '/' . $fixtureFilePath);
                     if ($resolvedPath) {
                         $fixtureFilePath = $resolvedPath;
                     }
                 }
                 $fixture = Injector::inst()->create('YamlFixture', $fixtureFilePath);
                 $fixture->writeInto($this->getFixtureFactory());
                 $this->fixtures[] = $fixture;
                 // backwards compatibility: Load first fixture into $this->fixture
                 if ($i == 0) {
                     $this->fixture = $fixture;
                 }
                 $i++;
             }
         }
         $this->logInWithPermission("ADMIN");
     }
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
     // turn off template debugging
     Config::inst()->update('SSViewer', 'source_file_comments', false);
     // Clear requirements
     Requirements::clear();
 }
Ejemplo n.º 19
0
 function testConditionalTemplateRequire()
 {
     $basePath = $this->getCurrentRelativePath();
     $backend = new RequirementsTest_Backend();
     $holder = Requirements::backend();
     Requirements::set_backend($backend);
     $data = new ArrayData(array('FailTest' => true));
     $data->renderWith('RequirementsTest_Conditionals');
     $backend->assertFileIncluded('css', $basePath . '/RequirementsTest_a.css');
     $backend->assertFileIncluded('js', array($basePath . '/RequirementsTest_b.js', $basePath . '/RequirementsTest_c.js'));
     $backend->assertFileNotIncluded('js', $basePath . '/RequirementsTest_a.js');
     $backend->assertFileNotIncluded('css', array($basePath . '/RequirementsTest_b.css', $basePath . '/RequirementsTest_c.css'));
     $backend->clear();
     $data = new ArrayData(array('FailTest' => false));
     $data->renderWith('RequirementsTest_Conditionals');
     $backend->assertFileNotIncluded('css', $basePath . '/RequirementsTest_a.css');
     $backend->assertFileNotIncluded('js', array($basePath . '/RequirementsTest_b.js', $basePath . '/RequirementsTest_c.js'));
     $backend->assertFileIncluded('js', $basePath . '/RequirementsTest_a.js');
     $backend->assertFileIncluded('css', array($basePath . '/RequirementsTest_b.css', $basePath . '/RequirementsTest_c.css'));
     Requirements::set_backend($holder);
 }
 public function testNoTestsDoesNotIncludeYepnope()
 {
     Yepnope::eval_yepnope();
     $scripts = Requirements::get_custom_scripts();
     $javascripts = Requirements::backend()->get_javascript();
     $this->assertEquals('', $scripts, 'YepNope output found, even though no test were added');
     $this->assertEquals(array(), $javascripts, 'YepNope lib was included, even though no tests were added');
 }
 /**
  * Iterate through 'block' key in config.requirements and block each script.
  *
  * @param array $block map of paths to block.
  * @return array of blocked scripts as ['js' => 'path'] type entries
  */
 protected static function block(array $block)
 {
     if ($block) {
         $blocked = $scriptTypes = static::include_script_types();
         $required = array_merge($scriptTypes, [self::FileTypeCSS => \Requirements::backend()->get_css(), self::FileTypeJavascript => \Requirements::backend()->get_javascript(), self::FileTypeJavascriptTemplate => \Requirements::backend()->get_custom_scripts()]);
         foreach ($scriptTypes as $fileType => $_) {
             foreach ($block as $path) {
                 $path = static::requirement_path($path);
                 foreach ($required[$fileType] as $require) {
                     if (fnmatch($path, $require)) {
                         $blocked[$fileType][] = $require;
                         \Requirements::block($required);
                     }
                 }
             }
         }
         return $blocked;
     }
     return [];
 }
 /**
  * Setter method for changing the Requirements backend
  *
  * @param Requirements_Backend $backend
  */
 public static function set_backend(Requirements_Backend $backend)
 {
     self::$backend = $backend;
 }
 /**
  * Load all the template variables into the internal variables, including
  * the template into body.	Called before send() or debugSend()
  * $isPlain=true will cause the template to be ignored, otherwise the GenericEmail template will be used
  * and it won't be plain email :)
  *
  * This function is updated to rewrite urls in a safely manner and inline css.
  * It will also changed the requirements backend to avoid requiring stuff in the html.
  */
 protected function parseVariables($isPlain = false)
 {
     $origState = Config::inst()->get('SSViewer', 'source_file_comments');
     Config::inst()->update('SSViewer', 'source_file_comments', false);
     // Workaround to avoid clutter in our rendered html
     $backend = Requirements::backend();
     Requirements::set_backend(new MandrillRequirementsBackend());
     if (!$this->parseVariables_done) {
         $this->parseVariables_done = true;
         if (!$this->original_body) {
             $this->original_body = $this->body;
         }
         // Parse $ variables in the base parameters
         $data = $this->templateData();
         // Process a .SS template file
         $fullBody = $this->original_body;
         if ($this->parse_body) {
             try {
                 $viewer = new SSViewer_FromString($fullBody);
                 $fullBody = $viewer->process($data);
             } catch (Exception $ex) {
                 SS_Log::log($ex->getMessage(), SS_Log::DEBUG);
             }
             // Also parse the email title
             try {
                 $viewer = new SSViewer_FromString($this->subject);
                 $this->subject = $viewer->process($data);
             } catch (Exception $ex) {
                 SS_Log::log($ex->getMessage(), SS_Log::DEBUG);
             }
             if ($this->callout) {
                 try {
                     $viewer = new SSViewer_FromString($this->callout);
                     $this->callout = $viewer->process($data);
                 } catch (Exception $ex) {
                     SS_Log::log($ex->getMessage(), SS_Log::DEBUG);
                 }
             }
             if ($this->sidebar) {
                 try {
                     $viewer = new SSViewer_FromString($this->sidebar);
                     $this->sidebar = $viewer->process($data);
                 } catch (Exception $ex) {
                     SS_Log::log($ex->getMessage(), SS_Log::DEBUG);
                 }
             }
         }
         if ($this->ss_template && !$isPlain) {
             // Requery data so that updated versions of To, From, Subject, etc are included
             $data = $this->templateData();
             $template = new SSViewer($this->ss_template);
             if ($template->exists()) {
                 // Make sure we included the parsed body into layout
                 $data->setField('Body', $fullBody);
                 try {
                     $fullBody = $template->process($data);
                 } catch (Exception $ex) {
                     SS_Log::log($ex->getMessage(), SS_Log::DEBUG);
                 }
             }
         }
         // Rewrite relative URLs
         $this->body = self::rewriteURLs($fullBody);
     }
     Config::inst()->update('SSViewer', 'source_file_comments', $origState);
     Requirements::set_backend($backend);
     return $this;
 }
 /**
  * Set this store as the new asset backend
  *
  * @param string $basedir Basedir to store assets, which will be placed beneath 'assets' folder
  */
 public static function activate($basedir)
 {
     // Assign this as the new store
     $publicAdapter = new PublicAssetAdapter(ASSETS_PATH . '/' . $basedir);
     $publicFilesystem = new Filesystem($publicAdapter, ['visibility' => AdapterInterface::VISIBILITY_PUBLIC]);
     $protectedAdapter = new ProtectedAssetAdapter(ASSETS_PATH . '/' . $basedir . '/.protected');
     $protectedFilesystem = new Filesystem($protectedAdapter, ['visibility' => AdapterInterface::VISIBILITY_PRIVATE]);
     $backend = new AssetStoreTest_SpyStore();
     $backend->setPublicFilesystem($publicFilesystem);
     $backend->setProtectedFilesystem($protectedFilesystem);
     Injector::inst()->registerService($backend, 'AssetStore');
     // Assign flysystem backend to generated asset handler at the same time
     $generated = new FlysystemGeneratedAssetHandler();
     $generated->setFilesystem($publicFilesystem);
     Injector::inst()->registerService($generated, 'GeneratedAssetHandler');
     Requirements::backend()->setAssetHandler($generated);
     // Disable legacy and set defaults
     Config::inst()->remove(get_class(new FlysystemAssetStore()), 'legacy_filenames');
     Config::inst()->update('Director', 'alternate_base_url', '/');
     DBFile::config()->force_resample = false;
     File::config()->force_resample = false;
     self::reset();
     self::$basedir = $basedir;
     // Ensure basedir exists
     \Filesystem::makeFolder(self::base_path());
 }
 public function testRequestsClientToken()
 {
     $this->sut->getFormFields($this->cart);
     $js = Requirements::backend()->get_custom_scripts();
     $this->assertContains('abc123', $js);
 }