public function setUp() { parent::setUp(); $this->logInWithPermission('ADMIN'); Versioned::set_stage(Versioned::DRAFT); // Set backend root to /AssetFieldTest AssetStoreTest_SpyStore::activate('AssetFieldTest'); $create = function ($path) { Filesystem::makeFolder(dirname($path)); $fh = fopen($path, "w+"); fwrite($fh, str_repeat('x', 1000000)); fclose($fh); }; // Write all DBFile references foreach (AssetFieldTest_Object::get() as $object) { $path = AssetStoreTest_SpyStore::getLocalPath($object->File); $create($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); $create($path); } }
public function testEnableWithCustomClasses() { FulltextSearchable::enable(array('SilverStripe\\Assets\\File')); $this->assertTrue(File::has_extension('SilverStripe\\ORM\\Search\\FulltextSearchable')); File::remove_extension('SilverStripe\\ORM\\Search\\FulltextSearchable'); $this->assertFalse(File::has_extension('SilverStripe\\ORM\\Search\\FulltextSearchable')); }
protected function getFormFields(Controller $controller, $name, $context = []) { $record = $context['Record']; $fields = new FieldList(LiteralField::create('Thumbnail', $this->getIconMarkup($record)), LiteralField::create('FileSpecs', $this->getSpecsMarkup($record)), ReadonlyField::create("Title", File::singleton()->fieldLabel('Title')), ReadonlyField::create('Name', File::singleton()->fieldLabel('Filename')), ReadonlyField::create("Path", _t('AssetTableField.PATH', 'Path'), $this->getPath($record))); $this->invokeWithExtensions('updateFormFields', $fields, $controller, $name, $context); return $fields; }
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 width of this item * * @return int */ public function getWidth() { if ($this->file) { $width = $this->file->getWidth(); if ($width) { return $width; } } return $this->config()->insert_width; }
/** * Get the file component from the request * * @param HTTPRequest $request * @return string */ protected function parseFilename(HTTPRequest $request) { $filename = ''; $next = $request->param('Filename'); while ($next) { $filename = $filename ? File::join_paths($filename, $next) : $next; $next = $request->shift(); } if ($extension = $request->getExtension()) { $filename = $filename . "." . $extension; } return $filename; }
public function setUp() { parent::setUp(); Versioned::set_stage(Versioned::DRAFT); // Set backend root to /DataDifferencerTest AssetStoreTest_SpyStore::activate('DataDifferencerTest'); // Create a test files for each of the fixture references $files = File::get()->exclude('ClassName', 'SilverStripe\\Assets\\Folder'); foreach ($files as $file) { $fromPath = FRAMEWORK_PATH . '/tests/model/testimages/' . $file->Name; $destPath = AssetStoreTest_SpyStore::getLocalPath($file); // Only correct for test asset store Filesystem::makeFolder(dirname($destPath)); copy($fromPath, $destPath); } }
public function setUp() { parent::setUp(); // Set backend root to /HTMLEditorFieldTest AssetStoreTest_SpyStore::activate('HTMLEditorFieldTest'); // 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 files for each of the fixture references $files = File::get()->exclude('ClassName', 'SilverStripe\\Assets\\Folder'); foreach ($files as $file) { $fromPath = FRAMEWORK_PATH . '/tests/forms/images/' . $file->Name; $destPath = AssetStoreTest_SpyStore::getLocalPath($file); // Only correct for test asset store Filesystem::makeFolder(dirname($destPath)); copy($fromPath, $destPath); } }
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'); } }
public function setUp() { parent::setUp(); // Execute specific subclass if (get_class($this) == "ImageTest") { $this->markTestSkipped(sprintf('Skipping %s ', get_class($this))); return; } // Set backend root to /ImageTest AssetStoreTest_SpyStore::activate('ImageTest'); // Copy test images for each of the fixture references $files = File::get()->exclude('ClassName', 'SilverStripe\\Assets\\Folder'); foreach ($files as $image) { $filePath = AssetStoreTest_SpyStore::getLocalPath($image); // Only correct for test asset store $sourcePath = FRAMEWORK_PATH . '/tests/model/testimages/' . $image->Name; if (!file_exists($filePath)) { SSFilesystem::makeFolder(dirname($filePath)); if (!copy($sourcePath, $filePath)) { user_error('Failed to copy test images', E_USER_ERROR); } } } }
public function testPublicAdapter() { $_SERVER['SERVER_SOFTWARE'] = 'Apache/2.2.22 (Win64) PHP/5.3.13'; $adapter = new PublicAssetAdapter($this->rootDir); $this->assertFileExists($this->rootDir . '/.htaccess'); $this->assertFileNotExists($this->rootDir . '/web.config'); $htaccess = $adapter->read('.htaccess'); $content = $htaccess['contents']; // Allowed extensions set $this->assertContains('RewriteCond %{REQUEST_URI} !\\.(?i:', $content); foreach (File::config()->allowed_extensions as $extension) { $this->assertRegExp('/\\b' . preg_quote($extension) . '\\b/', $content); } // Rewrite rules $this->assertContains('RewriteRule .* ../framework/main.php?url=%1 [QSA]', $content); $this->assertContains('RewriteRule error[^\\\\/]*\\.html$ - [L]', $content); // Test flush restores invalid content \file_put_contents($this->rootDir . '/.htaccess', '# broken content'); $adapter->flush(); $htaccess2 = $adapter->read('.htaccess'); $this->assertEquals($content, $htaccess2['contents']); // Test URL $this->assertEquals('/assets/AssetAdapterTest/file.jpg', $adapter->getPublicUrl('file.jpg')); }
/** * Looser check validation that doesn't do is_upload_file() * checks as we're faking a POST request that PHP didn't generate * itself. * * @return boolean */ public function validate() { $pathInfo = pathinfo($this->tmpFile['name']); // filesize validation if (!$this->isValidSize()) { $ext = isset($pathInfo['extension']) ? $pathInfo['extension'] : ''; $arg = File::format_size($this->getAllowedMaxFileSize($ext)); $this->errors[] = _t('File.TOOLARGE', 'File size is too large, maximum {size} allowed', 'Argument 1: File size (e.g. 1MB)', array('size' => $arg)); return false; } // extension validation if (!$this->isValidExtension()) { $this->errors[] = _t('File.INVALIDEXTENSION_SHORT', 'Extension is not allowed'); return false; } return true; }
/** * Limit allowed file extensions by specifying categories of file types. * These may be 'image', 'image/supported', 'audio', 'video', 'archive', 'flash', or 'document' * See {@link File::$allowed_extensions} for details of allowed extensions * for each of these categories * * @param string $category Category name * @param string,... $categories Additional category names * @return $this */ public function setAllowedFileCategories($category) { $extensions = File::get_category_extensions(func_get_args()); return $this->setAllowedExtensions($extensions); }
/** * @param File $record * @return FormAction */ protected function getInsertAction($record) { if ($record && $record->isInDB() && $record->canEdit()) { return FormAction::create('insert', _t('CMSMain.INSERT', 'Insert file'))->setSchemaData(['data' => ['buttonStyle' => 'primary']]); } return null; }
/** * @return Upload */ protected function getUpload() { $upload = Upload::create(); $upload->getValidator()->setAllowedExtensions(array_filter(File::config()->get('allowed_extensions'))); return $upload; }
/** * Returns the size of the file type in an appropriate format. * * @return string|false String value, or false if doesn't exist */ public function getSize() { $size = $this->getAbsoluteSize(); if ($size) { return File::format_size($size); } return false; }
/** * 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); }
/** * Safely encodes the File object with all standard fields required * by the front end * * @param string $filename * @param string $hash * @param string $variant * @return array Encoded list of file attributes */ protected function encodeAssetAttributes($filename, $hash, $variant) { // Force regeneration of file thumbnail for this tuple (without saving into db) $object = DBFile::create(); $object->setValue(array('Filename' => $filename, 'Hash' => $hash, 'Variant' => $variant)); return array('filename' => $filename, 'hash' => $hash, 'variant' => $variant, 'name' => $object->getBasename(), 'url' => $object->getURL(), 'thumbnail_url' => $object->ThumbnailURL($this->getPreviewMaxWidth(), $this->getPreviewMaxHeight()), 'size' => $object->getAbsoluteSize(), 'type' => File::get_file_type($object->getFilename()), 'buttons' => (string) $this->renderWith($this->getTemplateFileButtons()), 'fieldname' => $this->getName()); }
/** * Gets files filtered by a given parent with the allowed extensions * * @param int $parentID * @return DataList */ protected function getFiles($parentID = null) { $exts = $this->getAllowedExtensions(); $dotExts = array_map(function ($ext) { return ".{$ext}"; }, $exts); $files = File::get()->filter('Name:EndsWith', $dotExts); // Limit by folder (if required) if ($parentID) { $files = $files->filter('ParentID', $parentID); } return $files; }
/** * Build "details" formfield tab * * @param File $record * @param array $context * @return Tab */ protected function getFormFieldDetailsTab($record, $context = []) { return Tab::create('Details', TextField::create('Name', File::singleton()->fieldLabel('Filename'))); }
public function testJoinPaths() { $this->assertEquals('name/file.jpg', File::join_paths('/name', 'file.jpg')); $this->assertEquals('name/file.jpg', File::join_paths('name', 'file.jpg')); $this->assertEquals('name/file.jpg', File::join_paths('/name', '/file.jpg')); $this->assertEquals('name/file.jpg', File::join_paths('name/', '/', 'file.jpg')); $this->assertEquals('file.jpg', File::join_paths('/', '/', 'file.jpg')); $this->assertEquals('', File::join_paths('/', '/')); }
/** * Get the MIME type based on a file's extension. If the finfo class exists in PHP, and the file * exists relative to the project root, then use that extension, otherwise fallback to a list of * commonly known MIME types. * * @param string $filename * * @return string */ public static function get_mime_type($filename) { // If the finfo module is compiled into PHP, use it. $path = BASE_PATH . DIRECTORY_SEPARATOR . $filename; if (class_exists('finfo') && file_exists($path)) { $finfo = new finfo(FILEINFO_MIME_TYPE); return $finfo->file($path); } // Fallback to use the list from the HTTP.yml configuration and rely on the file extension // to get the file mime-type $ext = File::get_file_extension($filename); // Get the mime-types $mimeTypes = HTTP::config()->get('MimeTypes'); // The mime type doesn't exist if (!isset($mimeTypes[$ext])) { return 'application/unknown'; } return $mimeTypes[$ext]; }
/** * 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 GeneratedAssetHandler(); $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('SilverStripe\\Control\\Director', 'alternate_base_url', '/'); DBFile::config()->force_resample = false; File::config()->force_resample = false; self::reset(); self::$basedir = $basedir; // Ensure basedir exists SSFilesystem::makeFolder(self::base_path()); }
/** * @param int $folderID The ID of the folder to display. * @return FormField */ protected function getListField($folderID) { // Generate the folder selection field. /** @skipUpgrade */ $folderField = new TreeDropdownField('ParentID', _t('HTMLEditorField.FOLDER', 'Folder'), 'SilverStripe\\Assets\\Folder'); $folderField->setValue($folderID); // Generate the file list field. $config = GridFieldConfig::create(); $config->addComponent(new GridFieldSortableHeader()); $config->addComponent(new GridFieldFilterHeader()); $config->addComponent($colsComponent = new GridFieldDataColumns()); $colsComponent->setDisplayFields(array('StripThumbnail' => '', 'Title' => File::singleton()->fieldLabel('Title'), 'Created' => File::singleton()->fieldLabel('Created'), 'Size' => File::singleton()->fieldLabel('Size'))); $colsComponent->setFieldCasting(array('Created' => 'DBDatetime->Nice')); // Set configurable pagination for file list field $pageSize = Config::inst()->get(get_class($this), 'page_size'); $config->addComponent(new GridFieldPaginator($pageSize)); // If relation is to be autoset, we need to make sure we only list compatible objects. $baseClass = $this->parent->getRelationAutosetClass(); // Create the data source for the list of files within the current directory. $files = DataList::create($baseClass)->exclude('ClassName', 'SilverStripe\\Assets\\Folder'); if ($folderID) { $files = $files->filter('ParentID', $folderID); } $fileField = new GridField('Files', false, $files, $config); $fileField->setAttribute('data-selectable', true); if ($this->parent->getAllowedMaxFileNumber() !== 1) { $fileField->setAttribute('data-multiselect', true); } $selectComposite = new CompositeField($folderField, $fileField); return $selectComposite; }
public function getSize() { if ($this->size) { return File::format_size($this->size); } return parent::getSize(); }
/** * Render server configuration file from a template file * * @param string $template * @return string Rendered results */ protected function renderTemplate($template) { // Build allowed extensions $allowedExtensions = new ArrayList(); foreach (File::config()->allowed_extensions as $extension) { if ($extension) { $allowedExtensions->push(new ArrayData(array('Extension' => preg_quote($extension)))); } } $viewer = new SSViewer(array($template)); return (string) $viewer->process(new ArrayData(array('AllowedExtensions' => $allowedExtensions))); }