Version: current

# Class File

This class handles the representation of a File within Sapphire Note: The files are stored in the assets/ directory, but sapphire looks at the db object to gather information about a file such as URL It then uses this for all processing functions (like image manipulation).

  Object
  ViewableData implements IteratorAggregate
  DataObject implements DataObjectInterface, i18nEntityProvider
  File

### Direct known subclasses

`FLV`, `Folder`, `Image`, `MP3`

### Indirect known subclasses

`Image_Cached`, `MediawebPage_Image`, `VideoFile`

Package: sapphire\filesystem
Located at sapphire/filesystem/File.php

## Methods summary

`public static mixed` | # `find( mixed $filename )` Find a File object by the given filename. Find a File object by the given filename. #### Returns `mixed` null if not found, File object of found file
`public` | # `Link( mixed $action = null )`
`public` | # `RelativeLink( mixed $action = null )`
`public` | # `TreeTitle( )`
`public` | # `BackLinkTrackingCount( )`
`protected` | # `onBeforeDelete( )` Event handler called before deleting from the database. You can overload this to clean up or otherwise process data before delete this record. Don't forget to call parent::onBeforeDelete(), though! Event handler called before deleting from the database. You can overload this to clean up or otherwise process data before delete this record. Don't forget to call parent::onBeforeDelete(), though! #### Overrides `DataObject::onBeforeDelete`
`protected` | # `onAfterDelete( )` #### Overrides `DataObject::onAfterDelete`
`public boolean` | # `canView( `Member` $member = null )` #### Parameters $member Member $member #### Returns `boolean` boolean #### Overrides `DataObject::canView`
`public boolean` | # `canEdit( `Member` $member = null )` Returns true if the following conditions are met: CMS_ACCESS_AssetAdmin Returns true if the following conditions are met: CMS_ACCESS_AssetAdmin #### Parameters $member Member $member #### Returns `boolean` boolean #### Overrides `DataObject::canEdit`
`public boolean` | # `canCreate( `Member` $member = null )` #### Parameters $member Member $member #### Returns `boolean` boolean #### Overrides `DataObject::canCreate`
`public boolean` | # `canDelete( `Member` $member = null )` #### Parameters $member Member $member #### Returns `boolean` boolean #### Overrides `DataObject::canDelete`
`public` | # `appCategory( )`
`public` | # `CMSThumbnail( )`
`public` | # `Icon( )` Return the URL of an icon for the file type Return the URL of an icon for the file type
`public` | # `onAfterUpload( )` Should be called after the file was uploaded Should be called after the file was uploaded
`public` | # `deleteDatabaseOnly( )` Delete the database record (recursively for folders) without touching the filesystem Delete the database record (recursively for folders) without touching the filesystem
`protected` | # `onBeforeWrite( )` Event handler called before deleting from the database. You can overload this to clean up or otherwise process data before delete this record. Don't forget to call parent::onBeforeWrite(), though! Event handler called before deleting from the database. You can overload this to clean up or otherwise process data before delete this record. Don't forget to call parent::onBeforeWrite(), though! #### Overrides `DataObject::onBeforeWrite`
`public` | # `collateDescendants( condition $condition, collator & $collator )` Collate selected descendants of this page. $condition will be evaluated on each descendant, and if it is succeeds, that item will be added to the $collator array. Collate selected descendants of this page. $condition will be evaluated on each descendant, and if it is succeeds, that item will be added to the $collator array. #### Parameters $condition condition The PHP condition to be evaluated. The page will be called $item $collator collator An array, passed by reference, to collect all of the matching descendants.
`public` | # `setName( mixed $name )` Setter function for Name. Automatically sets a default title. Setter function for Name. Automatically sets a default title.
`protected` | # `resetFilename( mixed $renamePhysicalFile = true )` Change a filename, moving the file if appropriate. Change a filename, moving the file if appropriate. #### Parameters $renamePhysicalFile $renamePhysicalFile Set this to false if you don't want to rename the physical file. Used when calling resetFilename() on the children of a folder.
`protected` | # `autosetFilename( )` Set the Filename field without manipulating the filesystem. Set the Filename field without manipulating the filesystem.
`public` | # `setField( string $field, mixed $value )` Set the value of the field Called by `ViewableData::__set()` and any setFieldName() methods you might create. Set the value of the field Called by `ViewableData::__set()` and any setFieldName() methods you might create. #### Parameters $field string $fieldName Name of the field $value mixed $val New field value #### Overrides `DataObject::setField`
`protected` | # `updateLinks( mixed $old, mixed $new )` Rewrite links to the $old file to now point to the $new file Rewrite links to the $old file to now point to the $new file
`public` | # `setParentID( mixed $parentID )`
`public string` | # `getAbsoluteURL( )` Gets the absolute URL accessible through the web. Gets the absolute URL accessible through the web. #### Returns `string` string #### Uses ``Director::absoluteBaseURL()``
`public string` | # `getURL( )` Gets the relative URL accessible through the web. Gets the relative URL accessible through the web. #### Returns `string` string #### Uses ``Director::baseURL()``
`public` | # `getLinkedURL( )` Return the last 50 characters of the URL Return the last 50 characters of the URL
`public` | # `getFullPath( )`
`public String` | # `getRelativePath( )` Returns Returns #### Returns `String` String
`public` | # `DeleteLink( )`
`public` | # `getFilename( )`
`public` | # `setFilename( mixed $val )`
`public` | # `getExtension( )`
`public static string` | # `get_file_extension( string $filename )` Gets the extension of a filepath or filename, by stripping away everything before the last "dot". Gets the extension of a filepath or filename, by stripping away everything before the last "dot". #### Parameters $filename string $filename #### Returns `string` string
`public string` | # `getFileType( )` Return the type of file for the given extension on the current file name. Return the type of file for the given extension on the current file name. #### Returns `string` string
`public` | # `getSize( )` Returns the size of the file type in an appropriate format. Returns the size of the file type in an appropriate format.
`public static` | # `format_size( mixed $size )`
`public integer` | # `getAbsoluteSize( )` Return file size in bytes. Return file size in bytes. #### Returns `integer` int
`public mixed` | # `instance_get( string $filter = "", string $sort = "", string $join = "", string $limit = "", string $containerClass = "DataObjectSet", mixed $having = "" )` We've overridden the DataObject::get function for File so that the very large content field is excluded! We've overridden the DataObject::get function for File so that the very large content field is excluded! #### Deprecated alternative_instance_get() #### Parameters $filter string $filter A filter to be inserted into the WHERE clause. $sort string $sort A sort expression to be inserted into the ORDER BY clause. If omitted, self::$default_sort will be used. $join string $join A single join clause. This can be used for filtering, only 1 instance of each DataObject will be returned. $limit string $limit A limit expression to be inserted into the LIMIT clause. $containerClass string $containerClass The container class to return the results in. $having #### Returns `mixed` The objects matching the filter, in the class specified by $containerClass #### Overrides `DataObject::instance_get`
`public` | # `flushCache( )` Flush the cached results for all relations (has_one, has_many, many_many) Also clears any cached aggregate data Flush the cached results for all relations (has_one, has_many, many_many) Also clears any cached aggregate data #### Overrides `DataObject::flushCache`
`public array|string` | # `fieldLabels( boolean $includerelations = true )` #### Parameters $includerelations boolean $includerelations a boolean value to indicate if the labels returned include relation fields #### Returns `array|string` Array of all element labels if no argument given, otherwise the label of the field #### Overrides `DataObject::fieldLabels`
`public A` | # `validate( )` Validate the current object. Validate the current object. By default, there is no validation - objects are always valid! However, you can overload this method in your DataObject sub-classes to specify custom validation. Invalid objects won't be able to be written - a warning will be thrown and no write will occur. onBeforeWrite() and onAfterWrite() won't get called either. It is expected that you call validate() in your own application to test that an object is valid before attempting a write, and respond appropriately if it isnt'. #### Returns `A` `ValidationResult` object #### Overrides `DataObject::validate`
`public `FieldSet`` | # `uploadMetadataFields( )` Allow custom fields for uploads in `AssetAdmin`. Similar to `DataObject::getCMSFields()`, but a more restricted set of fields which can be reliably set on any file type. Allow custom fields for uploads in `AssetAdmin`. Similar to `DataObject::getCMSFields()`, but a more restricted set of fields which can be reliably set on any file type. Needs to be enabled through `AssetAdmin::$metadata_upload_enabled` #### Returns ``FieldSet`` FieldSet
`public` | # `getUsageCount( )`

### Methods inherited from DataObject

`Aggregate()`, `RelationshipAggregate()`, `__construct()`, `baseTable()`, `belongs_to()`, `buildDataObjectSet()`, `buildSQL()`, `can()`, `castedUpdate()`, `composite_fields()`, `context_obj()`, `customDatabaseFields()`, `custom_database_fields()`, `data()`, `databaseFields()`, `databaseIndexes()`, `database_extensions()`, `database_fields()`, `db()`, `dbObject()`, `debug()`, `defaultSearchFilters()`, `defineMethods()`, `delete()`, `delete_by_id()`, `destroy()`, `disableCMSFieldsExtensions()`, `disable_subclass_access()`, `duplicate()`, `enableCMSFieldsExtensions()`, `enable_subclass_access()`, `exists()`, `extendedSQL()`, `fieldLabel()`, `flush_and_destroy_cache()`, `forceChange()`, `get()`, `getAllFields()`, `getCMSActions()`, `getCMSFields()`, `getChangedFields()`, `getClassAncestry()`, `getComponent()`, `getComponents()`, `getComponentsQuery()`, `getDefaultSearchContext()`, `getField()`, `getFrontEndFields()`, `getManyManyComponents()`, `getManyManyComponentsQuery()`, `getManyManyFilter()`, `getManyManyJoin()`, `getRemoteJoinField()`, `getReverseAssociation()`, `getTitle()`, `get_by_id()`, `get_one()`, `get_validation_enabled()`, `hasDatabaseField()`, `hasField()`, `hasOwnTableDatabaseField()`, `hasValue()`, `has_many()`, `has_one()`, `has_own_table()`, `i18n_plural_name()`, `i18n_singular_name()`, `inheritedDatabaseFields()`, `instance_get_one()`, `isChanged()`, `isEmpty()`, `isInDB()`, `is_composite_field()`, `many_many()`, `many_many_extraFields()`, `merge()`, `newClassInstance()`, `onAfterWrite()`, `plural_name()`, `populateDefaults()`, `provideI18nEntities()`, `relObject()`, `requireDefaultRecords()`, `requireTable()`, `reset()`, `scaffoldFormFields()`, `scaffoldSearchFields()`, `searchableFields()`, `setCastedField()`, `setClassName()`, `setComponent()`, `set_context_obj()`, `set_validation_enabled()`, `singular_name()`, `summaryFields()`, `toMap()`, `update()`, `write()`, `writeComponents()`, `writeWithoutVersion()`

### Methods inherited from ViewableData

`ATT_val()`, `BaseHref()`, `CSSClasses()`, `ColumnBreak()`, `ColumnCalc()`, `ColumnNumber()`, `ColumnPad()`, `ColumnPos()`, `CurrentMember()`, `CurrentPage()`, `Debug()`, `Even()`, `EvenOdd()`, `First()`, `FirstLast()`, `HasPerm()`, `IsAjax()`, `JS_val()`, `Last()`, `Me()`, `Middle()`, `MiddleString()`, `Modulus()`, `MultipleOf()`, `Odd()`, `Pos()`, `RAW_val()`, `SQL_val()`, `ThemeDir()`, `ThemeName()`, `Top()`, `TotalItems()`, `XML_val()`, `__get()`, `__isset()`, `__set()`, `buildCastingCache()`, `cachedCall()`, `castingClass()`, `castingHelper()`, `castingHelperPair()`, `castingObjectCreator()`, `castingObjectCreatorPair()`, `customise()`, `escapeTypeForField()`, `getIterator()`, `getSecurityID()`, `getXMLValues()`, `i18nLocale()`, `iteratorProperties()`, `obj()`, `renderWith()`, `setCustomisedObj()`

### Methods inherited from Object

`__call()`, `__toString()`, `__wakeup()`, `addMethodsFrom()`, `addStaticVars()`, `addWrapperMethod()`, `add_extension()`, `add_static_var()`, `allMethodNames()`, `cacheToFile()`, `cacheToFileWithArgs()`, `clearCache()`, `combined_static()`, `create()`, `createMethod()`, `create_from_string()`, `extInstance()`, `extend()`, `getCustomClass()`, `getExtensionInstance()`, `getExtensionInstances()`, `get_extensions()`, `get_static()`, `hasExtension()`, `hasMethod()`, `has_extension()`, `invokeWithExtensions()`, `is_a()`, `loadCache()`, `parentClass()`, `parse_class_spec()`, `remove_extension()`, `sanitiseCachename()`, `saveCache()`, `set_stat()`, `set_static()`, `set_uninherited()`, `stat()`, `strong_create()`, `uninherited()`, `uninherited_static()`, `useCustomClass()`

### Magic methods summary

## Properties summary

`public static string` | $default_sort | # The default sort expression. This will be inserted in the ORDER BY clause of a SQL query if no other sort expression is provided. The default sort expression. This will be inserted in the ORDER BY clause of a SQL query if no other sort expression is provided.
`public static string` | $singular_name | # Human-readable singular name. Human-readable singular name.
`public static string` | $plural_name | # Human-readable pluaral name Human-readable pluaral name
`public static array` | $db | # Database field definitions. This is a map from field names to field type. The field type should be a class that extends . Database field definitions. This is a map from field names to field type. The field type should be a class that extends .
`public static array` | $has_one | # One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a true one-to-one relationship you can add a `DataObject::$belongs_to` relationship on the child class. One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a true one-to-one relationship you can add a `DataObject::$belongs_to` relationship on the child class. Note that you cannot have a has_one and belongs_to relationship with the same name.
`public static array` | $has_many | # This defines a one-to-many relationship. It is a map of component name to the remote data class. This defines a one-to-many relationship. It is a map of component name to the remote data class. This relationship type does not actually create a data structure itself - you need to define a matching $has_one relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show which foreign key to use.
`public static array` | $many_many | # many-many relationship definitions. This is a map from component name to data type. many-many relationship definitions. This is a map from component name to data type.
`public static array` | $belongs_many_many | # The inverse side of a many-many relationship. This is a map from component name to data type. The inverse side of a many-many relationship. This is a map from component name to data type.
`public static array` | $defaults | # Inserts standard column-values when a DataObject is instanciated. Does not insert default records `DataObject::$default_records`. This is a map from fieldname to default value. Inserts standard column-values when a DataObject is instanciated. Does not insert default records `DataObject::$default_records`. This is a map from fieldname to default value. If you would like to change a default value in a sub-class, just specify it. - If you would like to disable the default value given by a parent class, set the default value to 0,'',or false in your subclass. Setting it to null won't work.
`public static array` | $extensions | # An array of extension names and parameters to be applied to this object upon construction. An array of extension names and parameters to be applied to this object upon construction. Example:
    public static $extensions = array (
      'Hierachy',
      "Version('Stage', 'Live')"
    );
Use `Object::add_extension()` to add extensions without access to the class code, e.g. to extend core classes. Extensions are instanciated together with the object and stored in `Object::$extension_instances`.
`public static array` | $indexes | # If a field is in this array, then create a database index on that field. This is a map from fieldname to index type. See SS_Database->requireIndex() and custom subclasses for details on the array notation. If a field is in this array, then create a database index on that field. This is a map from fieldname to index type. See SS_Database->requireIndex() and custom subclasses for details on the array notation.
`public static array` | $allowed_extensions | # #### See Upload->allowedExtensions
`public static boolean` | $apply_restrictions_to_admin | # If this is true, then restrictions set in $allowed_max_file_size and $allowed_extensions will be applied to users with admin privileges as well. If this is true, then restrictions set in $allowed_max_file_size and $allowed_extensions will be applied to users with admin privileges as well.
`protected static array` | $cache_file_fields | # Cached result of a "SHOW FIELDS" call in instance_get() for performance reasons. Cached result of a "SHOW FIELDS" call in instance_get() for performance reasons.

### Properties inherited from DataObject

`$allowed_actions`, `$ancestry`, `$api_access`, `$belongs_to`, `$brokenOnDelete`, `$brokenOnWrite`, `$cache_get_one`, `$cache_has_own_table`, `$cache_has_own_table_field`, `$casting`, `$componentCache`, `$components`, `$create_table_options`, `$default_records`, `$destroyed`, `$field_labels`, `$many_many_extraFields`, `$original`, `$record`, `$searchable_fields`, `$summary_fields`

### Properties inherited from ViewableData

`$customisedObject`, `$default_cast`, `$failover`, `$iteratorPos`, `$iteratorTotalItems`

### Properties inherited from Object

`$class`, `$extension_instances`

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -