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);
     }
 }
 /**
  * Get ID of target parent folder
  *
  * @return int
  */
 protected function getFolderID()
 {
     $folderName = $this->getFolderName();
     if (!$folderName) {
         return 0;
     }
     $folder = Folder::find_or_make($folderName);
     return $folder ? $folder->ID : 0;
 }
 /**
  * Build the file selection form.
  *
  * @skipUpgrade
  * @return Form
  */
 public function Form()
 {
     // Find out the requested folder ID.
     $folderID = $this->parent->getRequest()->requestVar('ParentID');
     if ($folderID === null && $this->parent->getDisplayFolderName()) {
         $folder = Folder::find_or_make($this->parent->getDisplayFolderName());
         $folderID = $folder ? $folder->ID : 0;
     }
     // Construct the form
     $action = new FormAction('doAttach', _t('UploadField.AttachFile', 'Attach file(s)'));
     $action->addExtraClass('ss-ui-action-constructive icon-accept');
     $form = new Form($this, 'Form', new FieldList($this->getListField($folderID)), new FieldList($action));
     // Add a class so we can reach the form from the frontend.
     $form->addExtraClass('uploadfield-form');
     return $form;
 }
 public function setUp()
 {
     parent::setUp();
     // Set backend root to /ImageTest
     AssetStoreTest_SpyStore::activate('ProtectedFileControllerTest');
     // Create a test folders for each of the fixture references
     foreach (Folder::get() as $folder) {
         /** @var Folder $folder */
         $filePath = AssetStoreTest_SpyStore::getLocalPath($folder);
         Filesystem::makeFolder($filePath);
     }
     // Create a test files for each of the fixture references
     foreach (File::get()->exclude('ClassName', 'SilverStripe\\Assets\\Folder') as $file) {
         /** @var File $file */
         $path = AssetStoreTest_SpyStore::getLocalPath($file);
         Filesystem::makeFolder(dirname($path));
         $fh = fopen($path, "w+");
         fwrite($fh, str_repeat('x', 1000000));
         fclose($fh);
         // Create variant for each file
         $this->getAssetStore()->setFromString(str_repeat('y', 100), $file->Filename, $file->Hash, 'variant');
     }
 }
 /**
  * Check if file exists, both checking filtered filename and exact filename
  *
  * @param string $originalFile Filename
  * @return bool
  */
 protected function checkFileExists($originalFile)
 {
     // Check both original and safely filtered filename
     $nameFilter = FileNameFilter::create();
     $filteredFile = $nameFilter->filter($originalFile);
     // Resolve expected folder name
     $folderName = $this->getFolderName();
     $folder = Folder::find_or_make($folderName);
     $parentPath = $folder ? $folder->getFilename() : '';
     // check if either file exists
     return File::find($parentPath . $originalFile) || File::find($parentPath . $filteredFile);
 }
 /**
  * Get the children of this folder that are also folders.
  *
  * @return DataList
  */
 public function ChildFolders()
 {
     return Folder::get()->filter('ParentID', $this->ID);
 }
 public function testIllegalFilenames()
 {
     // Test that generating a filename with invalid characters generates a correctly named folder.
     $folder = Folder::find_or_make('/FolderTest/EN_US Lang');
     $this->assertEquals('FolderTest/EN-US-Lang/', $folder->getFilename());
     // Test repeatitions of folder
     $folder2 = Folder::find_or_make('/FolderTest/EN_US Lang');
     $this->assertEquals($folder->ID, $folder2->ID);
     $folder3 = Folder::find_or_make('/FolderTest/EN--US_L!ang');
     $this->assertEquals($folder->ID, $folder3->ID);
     $folder4 = Folder::find_or_make('/FolderTest/EN-US-Lang');
     $this->assertEquals($folder->ID, $folder4->ID);
 }
 /**
  * Creates a single file based on a form-urlencoded upload.
  *
  * @param HTTPRequest $request
  * @return HTTPRequest|HTTPResponse
  */
 public function apiCreateFile(HTTPRequest $request)
 {
     $data = $request->postVars();
     $upload = $this->getUpload();
     // CSRF check
     $token = SecurityToken::inst();
     if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) {
         return new HTTPResponse(null, 400);
     }
     // Check parent record
     /** @var Folder $parentRecord */
     $parentRecord = null;
     if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) {
         $parentRecord = Folder::get()->byID($data['ParentID']);
     }
     $data['Parent'] = $parentRecord;
     $tmpFile = $request->postVar('Upload');
     if (!$upload->validate($tmpFile)) {
         $result = ['message' => null];
         $errors = $upload->getErrors();
         if ($message = array_shift($errors)) {
             $result['message'] = ['type' => 'error', 'value' => $message];
         }
         return (new HTTPResponse(json_encode($result), 400))->addHeader('Content-Type', 'application/json');
     }
     // TODO Allow batch uploads
     $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name']));
     /** @var File $file */
     $file = Injector::inst()->create($fileClass);
     // check canCreate permissions
     if (!$file->canCreate(null, $data)) {
         $result = ['message' => ['type' => 'error', 'value' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.CreatePermissionDenied', 'You do not have permission to add files')]];
         return (new HTTPResponse(json_encode($result), 403))->addHeader('Content-Type', 'application/json');
     }
     $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/');
     if (!$uploadResult) {
         $result = ['message' => ['type' => 'error', 'value' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.LoadIntoFileFailed', 'Failed to load file')]];
         return (new HTTPResponse(json_encode($result), 400))->addHeader('Content-Type', 'application/json');
     }
     $file->ParentID = $parentRecord ? $parentRecord->ID : 0;
     $file->write();
     $result = [$this->getObjectFromData($file)];
     return (new HTTPResponse(json_encode($result)))->addHeader('Content-Type', 'application/json');
 }
 public function testCreateWithFilenameWithSubfolder()
 {
     // Note: We can't use fixtures/setUp() for this, as we want to create the db record manually.
     // Creating the folder is necessary to avoid having "Filename" overwritten by setName()/setRelativePath(),
     // because the parent folders don't exist in the database
     $folder = Folder::find_or_make('/FileTest/');
     $testfilePath = BASE_PATH . '/assets/FileTest/CreateWithFilenameHasCorrectPath.txt';
     // Important: No leading slash
     $fh = fopen($testfilePath, "w");
     fwrite($fh, str_repeat('x', 1000000));
     fclose($fh);
     $file = new File();
     $file->setFromLocalFile($testfilePath);
     $file->ParentID = $folder->ID;
     $file->write();
     $this->assertEquals('CreateWithFilenameHasCorrectPath.txt', $file->Name, '"Name" property is automatically set from "Filename"');
     $this->assertEquals('FileTest/CreateWithFilenameHasCorrectPath.txt', $file->Filename, '"Filename" property remains unchanged');
     // TODO This should be auto-detected, see File->updateFilesystem()
     // $this->assertInstanceOf('Folder', $file->Parent(), 'Parent folder is created in database');
     // $this->assertFileExists($file->Parent()->getURL(), 'Parent folder is created on filesystem');
     // $this->assertEquals('FileTest', $file->Parent()->Name);
     // $this->assertInstanceOf('Folder', $file->Parent()->Parent(), 'Grandparent folder is created in database');
     // $this->assertFileExists($file->Parent()->Parent()->getURL(),
     // 'Grandparent folder is created on filesystem');
     // $this->assertEquals('assets', $file->Parent()->Parent()->Name);
 }