/**
  * Perform migration
  *
  * @param string $base Absolute base path (parent of assets folder). Will default to BASE_PATH
  * @return int Number of files successfully migrated
  */
 public function run($base = null)
 {
     if (empty($base)) {
         $base = BASE_PATH;
     }
     // Check if the File dataobject has a "Filename" field.
     // If not, cannot migrate
     /** @skipUpgrade */
     if (!DB::get_schema()->hasField('File', 'Filename')) {
         return 0;
     }
     // Set max time and memory limit
     increase_time_limit_to();
     increase_memory_limit_to();
     // Loop over all files
     $count = 0;
     $originalState = Versioned::get_reading_mode();
     Versioned::set_stage(Versioned::DRAFT);
     $filenameMap = $this->getFilenameArray();
     foreach ($this->getFileQuery() as $file) {
         // Get the name of the file to import
         $filename = $filenameMap[$file->ID];
         $success = $this->migrateFile($base, $file, $filename);
         if ($success) {
             $count++;
         }
     }
     Versioned::set_reading_mode($originalState);
     return $count;
 }
 public function setUp()
 {
     parent::setUp();
     $this->logInWithPermission('ADMIN');
     // Save versioned state
     $this->oldReadingMode = Versioned::get_reading_mode();
     Versioned::set_stage(Versioned::DRAFT);
     // Set backend root to /UploadFieldTest
     AssetStoreTest_SpyStore::activate('UploadFieldTest');
     // Set the File Name Filter replacements so files have the expected names
     Config::inst()->update('SilverStripe\\Assets\\FileNameFilter', 'default_replacements', array('/\\s/' => '-', '/_/' => '-', '/[^A-Za-z0-9+.\\-]+/' => '', '/[\\-]{2,}/' => '-', '/^[\\.\\-_]+/' => ''));
     // Create a test folders for each of the fixture references
     foreach (Folder::get() as $folder) {
         $path = AssetStoreTest_SpyStore::getLocalPath($folder);
         Filesystem::makeFolder($path);
     }
     // Create a test files for each of the fixture references
     $files = File::get()->exclude('ClassName', 'SilverStripe\\Assets\\Folder');
     foreach ($files as $file) {
         $path = AssetStoreTest_SpyStore::getLocalPath($file);
         Filesystem::makeFolder(dirname($path));
         $fh = fopen($path, "w+");
         fwrite($fh, str_repeat('x', 1000000));
         fclose($fh);
     }
 }
 /**
  * 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;
 }
 public function setUp()
 {
     //nest config and injector for each test so they are effectively sandboxed per test
     Config::nest();
     Injector::nest();
     $this->originalReadingMode = Versioned::get_reading_mode();
     // We cannot run the tests on this abstract class.
     if (get_class($this) == "SapphireTest") {
         $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(Config::inst()->get('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('SilverStripe\\CMS\\Controllers\\RootURLController')) {
         RootURLController::reset();
     }
     if (class_exists('Translatable')) {
         Translatable::reset();
     }
     Versioned::reset();
     DataObject::reset();
     if (class_exists('SilverStripe\\CMS\\Model\\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_';
     // Todo: this could be a special test model
     $this->model = DataModel::inst();
     // Set up fixture
     if ($fixtureFile || $this->usesDatabase) {
         if (!self::using_temp_db()) {
             self::create_temp_db();
         }
         singleton('SilverStripe\\ORM\\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();
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Injector::inst()->registerService($this->mailer, 'Mailer');
     Config::inst()->remove('Email', 'send_all_emails_to');
 }
 public function setUp()
 {
     //nest config and injector for each test so they are effectively sandboxed per test
     Config::nest();
     Injector::nest();
     $this->originalReadingMode = Versioned::get_reading_mode();
     // We cannot run the tests on this abstract class.
     if (get_class($this) == __CLASS__) {
         $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::config()->get('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);
     Cookie::config()->update('report_errors', false);
     if (class_exists('SilverStripe\\CMS\\Controllers\\RootURLController')) {
         RootURLController::reset();
     }
     if (class_exists('Translatable')) {
         Translatable::reset();
     }
     Versioned::reset();
     DataObject::reset();
     if (class_exists('SilverStripe\\CMS\\Model\\SiteTree')) {
         SiteTree::reset();
     }
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(Session::create(array()));
     }
     Security::$database_is_ready = null;
     // Add controller-name auto-routing
     // @todo Fix to work with namespaced controllers
     Director::config()->update('rules', array('$Controller//$Action/$ID/$OtherID' => '*'));
     $fixtureFiles = $this->getFixturePaths();
     // Todo: this could be a special test model
     $this->model = DataModel::inst();
     // Set up fixture
     if ($fixtureFiles || $this->usesDatabase) {
         if (!self::using_temp_db()) {
             self::create_temp_db();
         }
         DataObject::singleton()->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();
             }
         }
         foreach ($fixtureFiles as $fixtureFilePath) {
             $fixture = YamlFixture::create($fixtureFilePath);
             $fixture->writeInto($this->getFixtureFactory());
         }
         $this->logInWithPermission("ADMIN");
     }
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
     // turn off template debugging
     SSViewer::config()->update('source_file_comments', false);
     // Clear requirements
     Requirements::clear();
     // Set up email
     $this->mailer = new TestMailer();
     Injector::inst()->registerService($this->mailer, 'SilverStripe\\Control\\Email\\Mailer');
     Email::config()->remove('send_all_emails_to');
 }
 /**
  * Tests that reading mode persists between requests
  */
 public function testReadingPersistent()
 {
     $session = Injector::inst()->create('Session', array());
     $adminID = $this->logInWithPermission('ADMIN');
     $session->inst_set('loggedInAs', $adminID);
     // Set to stage
     Director::test('/?stage=Stage', null, $session);
     $this->assertEquals('Stage.Stage', $session->inst_get('readingMode'), 'Check querystring changes reading mode to Stage');
     Director::test('/', null, $session);
     $this->assertEquals('Stage.Stage', $session->inst_get('readingMode'), 'Check that subsequent requests in the same session remain in Stage mode');
     // Test live persists
     Director::test('/?stage=Live', null, $session);
     $this->assertEquals('Stage.Live', $session->inst_get('readingMode'), 'Check querystring changes reading mode to Live');
     Director::test('/', null, $session);
     $this->assertEquals('Stage.Live', $session->inst_get('readingMode'), 'Check that subsequent requests in the same session remain in Live mode');
     // Test that session doesn't redundantly store the default stage if it doesn't need to
     $session2 = Injector::inst()->create('Session', array());
     $session2->inst_set('loggedInAs', $adminID);
     Director::test('/', null, $session2);
     $this->assertArrayNotHasKey('readingMode', $session2->inst_changedData());
     Director::test('/?stage=Live', null, $session2);
     $this->assertArrayNotHasKey('readingMode', $session2->inst_changedData());
     // Test choose_site_stage
     unset($_GET['stage']);
     unset($_GET['archiveDate']);
     Session::set('readingMode', 'Stage.Stage');
     Versioned::choose_site_stage();
     $this->assertEquals('Stage.Stage', Versioned::get_reading_mode());
     Session::set('readingMode', 'Archive.2014-01-01');
     Versioned::choose_site_stage();
     $this->assertEquals('Archive.2014-01-01', Versioned::get_reading_mode());
     Session::clear('readingMode');
     Versioned::choose_site_stage();
     $this->assertEquals('Stage.Live', Versioned::get_reading_mode());
 }
 /**
  * Write the given record to the draft stage
  *
  * @param string $stage
  * @param boolean $forceInsert
  * @return int The ID of the record
  */
 public function writeToStage($stage, $forceInsert = false)
 {
     $oldMode = Versioned::get_reading_mode();
     Versioned::set_stage($stage);
     $owner = $this->owner;
     $owner->forceChange();
     $result = $owner->write(false, $forceInsert);
     Versioned::set_reading_mode($oldMode);
     return $result;
 }
 public function testVersionedCache()
 {
     $origReadingMode = Versioned::get_reading_mode();
     // Run without caching in stage to prove data is uncached
     $this->_reset(false);
     Versioned::set_stage(Versioned::DRAFT);
     $data = new SSViewerCacheBlockTest_VersionedModel();
     $data->setEntropy('default');
     $this->assertEquals('default Stage.Stage', SSViewer::execute_string('<% cached %>$Inspect<% end_cached %>', $data));
     $data = new SSViewerCacheBlockTest_VersionedModel();
     $data->setEntropy('first');
     $this->assertEquals('first Stage.Stage', SSViewer::execute_string('<% cached %>$Inspect<% end_cached %>', $data));
     // Run without caching in live to prove data is uncached
     $this->_reset(false);
     Versioned::set_stage(Versioned::LIVE);
     $data = new SSViewerCacheBlockTest_VersionedModel();
     $data->setEntropy('default');
     $this->assertEquals('default Stage.Live', $this->_runtemplate('<% cached %>$Inspect<% end_cached %>', $data));
     $data = new SSViewerCacheBlockTest_VersionedModel();
     $data->setEntropy('first');
     $this->assertEquals('first Stage.Live', $this->_runtemplate('<% cached %>$Inspect<% end_cached %>', $data));
     // Then with caching, initially in draft, and then in live, to prove that
     // changing the versioned reading mode doesn't cache between modes, but it does
     // within them
     $this->_reset(true);
     Versioned::set_stage(Versioned::DRAFT);
     $data = new SSViewerCacheBlockTest_VersionedModel();
     $data->setEntropy('default');
     $this->assertEquals('default Stage.Stage', $this->_runtemplate('<% cached %>$Inspect<% end_cached %>', $data));
     $data = new SSViewerCacheBlockTest_VersionedModel();
     $data->setEntropy('first');
     $this->assertEquals('default Stage.Stage', $this->_runtemplate('<% cached %>$Inspect<% end_cached %>', $data));
     Versioned::set_stage(Versioned::LIVE);
     $data = new SSViewerCacheBlockTest_VersionedModel();
     $data->setEntropy('first');
     $this->assertEquals('first Stage.Live', $this->_runtemplate('<% cached %>$Inspect<% end_cached %>', $data));
     $data = new SSViewerCacheBlockTest_VersionedModel();
     $data->setEntropy('second');
     $this->assertEquals('first Stage.Live', $this->_runtemplate('<% cached %>$Inspect<% end_cached %>', $data));
     Versioned::set_reading_mode($origReadingMode);
 }