Class File
This class handles the representation of a file on the filesystem within the
framework. Most of the methods also handle the Folder subclass.
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).
Security
Caution: It is recommended to disable any script execution in the "assets/" directory in the webserver configuration, to reduce the risk of exploits. See http://doc.silverstripe.org/secure-development#filesystem
Properties
- "Name": File name (including extension) or folder name. Should be the same as the actual filesystem.
- "Title": Optional title of the file (for display purposes only). Defaults to "Name".
- "Filename": Path of the file or folder, relative to the webroot. Usually starts with the "assets/" directory, and has no trailing slash. Defaults to the "assets/" directory plus "Name" property if not set. Setting the "Filename" property will override the "Name" property. The value should be in sync with "ParentID".
- "Content": Typically unused, but handy for a textual representation of files, e.g. for fulltext indexing of PDF documents.
- "ParentID": Points to a
Folderrecord. Should be in sync with "Filename". A ParentID=0 value points to the "assets/" folder, not the webroot.
Synchronization
Changes to a File database record can change the filesystem entry, but not
the other way around. If the filesystem path is renamed outside of SilverStripe,
there's no way for the database to recover this linkage. New physical files on
the filesystem can be "discovered" via Filesystem::sync(), the
equivalent File and Folder records are automatically created by
this method.
Certain property changes within the File API that can cause a "delayed"
filesystem change: The change is enforced in File::onBeforeWrite() later
on.
- setParentID()
- setFilename()
- setName()
It is recommended that you use DataObject::write() directly after setting any of
these properties, otherwise getters like File::getFullPath() and File::getRelativePath() will result paths that are inconsistent with the
filesystem.
Caution: Calling DataObject::delete() will also delete from the filesystem. Call
File::deleteDatabaseOnly() if you want to avoid this.
Creating Files and Folders
Typically both files and folders should be created first on the filesystem,
and then reflected in as database records. Folders can be created recursively
from sapphire both in the database and filesystem through Folder::findOrMake(). Ensure that you always set a "Filename" property when
writing to the database, leaving it out can lead to unexpected results.
- Object
-
ViewableData
implements
IteratorAggregate
-
DataObject
implements
DataObjectInterface,
i18nEntityProvider
-
File
Indirect known subclasses
Methods summary
public static
mixed
|
|
public
|
|
public
|
|
public
|
|
public
Integer
|
|
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 |
protected
|
|
public
boolean
|
|
public
boolean
|
|
public
boolean
|
|
public
boolean
|
|
public
String
|
#
appCategory( )
Returns a category based on the file extension. This can be useful when grouping files by type, showing icons on filelinks, etc. Possible group values are: "audio", "mov", "zip", "image". |
public
|
|
public
String
|
#
Icon( )
Return the relative URL of an icon for the file type, based on the |
public
|
|
public
|
#
deleteDatabaseOnly( )
Delete the database record (recursively for folders) without touching the filesystem |
protected
|
|
protected
|
#
onAfterWrite( )
Set name on filesystem. If the current object is a "Folder", will also update references to subfolders and contained file records (both in database and filesystem) |
public
|
#
updateFilesystem( )
Moving the file if appropriate according to updated database content. Throws an Exception if the new file already exists. |
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. |
public
|
#
setName( String $name )
Setter function for Name. Automatically sets a default title, and removes
characters that might be invalid on the filesystem. Also adds a suffix to the
name if the filename already exists on the filesystem, and is associated to a
different |
protected
|
#
updateLinks( String $old, String $new )
Rewrite links to the $old file to now point to the $new file. |
public
|
#
setParentID( mixed $parentID )
Does not change the filesystem itself, please use |
public
string
|
|
public
string
|
|
public
|
|
public
String
|
#
getFullPath( )
Returns an absolute filesystem path to the file. Use |
public
String
|
#
getRelativePath( )
Returns path relative to webroot. Serves as a "fallback" method to create the
"Filename" property if it isn't set. If no |
public
|
|
public
|
|
public
|
#
setFilename( mixed $val )
Does not change the filesystem itself, please use |
public
String
|
|
public static
string
|
#
get_file_extension( string $filename )
Gets the extension of a filepath or filename, by stripping away everything before the last "dot". Caution: Only returns the last extension in "double-barrelled" extensions (e.g. "gz" for "tar.gz"). |
public
string
|
|
public
|
|
public static
|
|
public
integer
|
|
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! |
public
|
#
flushCache( )
Flush the cached results for all relations (has_one, has_many, many_many) Also clears any cached aggregate data |
public
array|string
|
|
public
A
|
|
public
|
#
uploadMetadataFields( )
Allow custom fields for uploads in |
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(),
disable_subclass_access(),
duplicate(),
enable_subclass_access(),
exists(),
extendedCan(),
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(),
plural_name(),
populateDefaults(),
provideI18nEntities(),
relObject(),
requireDefaultRecords(),
requireTable(),
reset(),
scaffoldFormFields(),
scaffoldSearchFields(),
searchableFields(),
setCastedField(),
setClassName(),
setComponent(),
setField(),
set_context_obj(),
set_validation_enabled(),
singular_name(),
summaryFields(),
toMap(),
update(),
write(),
writeComponents(),
writeWithoutVersion()
Methods inherited from ViewableData
ATT_val(),
BaseHref(),
CSSClasses(),
CurrentMember(),
CurrentPage(),
Debug(),
Even(),
EvenOdd(),
First(),
FirstLast(),
HasPerm(),
IsAjax(),
JS_val(),
Last(),
Me(),
Middle(),
MiddleString(),
Modulus(),
MultipleOf(),
Odd(),
Pos(),
RAW_val(),
SQL_val(),
ThemeDir(),
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(),
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. |
public static
string
|
$singular_name |
#
Human-readable singular name. |
public static
string
|
$plural_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 . |
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
|
public static
array
|
$has_many |
#
This defines a one-to-many relationship. It is a map of component name to the remote data class. |
public static
array
|
$many_many |
#
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. |
public static
array
|
$defaults |
#
Inserts standard column-values when a DataObject is instanciated. Does not
insert default records |
public static
array
|
$extensions |
#
An array of extension names and parameters to be applied to this object upon construction. |
public static
array
|
$allowed_extensions |
#
List of allowed file extensions, enforced through Note: if you modify this, you should also change a configuration file in the assets directory. Otherwise, the files will be able to be uploaded but they won't be able to be served by the webserver. - If you are running Apahce you will need to change assets/.htaccess Instructions for the change you need to make are included in a comment in the config file. |
public static
If
|
$apply_restrictions_to_admin |
#
this is true, then restrictions set in $allowed_max_file_size and
|
protected static
array
|
$cache_file_fields |
#
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,
$indexes,
$many_many_extraFields,
$original,
$record,
$searchable_fields,
$summary_fields
Properties inherited from ViewableData
$customisedObject,
$default_cast,
$failover,
$iteratorPos,
$iteratorTotalItems
Comments
Use the Silverstripe Forum to ask questions.