SilverStripe 2.4 API Docs
  • Package
  • Class
  • Tree
  • Deprecated
Version: master
  • master
  • 3.1
  • 3.0
  • 2.4
  • tagfield

Packages

  • cms
    • assets
    • batchaction
    • batchactions
    • bulkloading
    • comments
    • content
    • core
    • export
    • publishers
    • reports
    • security
    • tasks
  • forms
    • actions
    • core
    • fields-basic
    • fields-dataless
    • fields-datetime
    • fields-files
    • fields-formatted
    • fields-formattedinput
    • fields-relational
    • fields-structural
    • transformations
    • validators
  • installer
  • None
  • PHP
  • sapphire
    • api
    • bulkloading
    • control
    • core
    • cron
    • dev
    • email
    • fields-formattedinput
    • filesystem
    • formatters
    • forms
    • i18n
    • integration
    • misc
    • model
    • parsers
    • search
    • security
    • tasks
    • testing
    • tools
    • validation
    • view
    • widgets

Classes

  • Archive
  • File
  • Filesystem
  • FlushGeneratedImagesTask
  • Folder
  • Folder_UnusedAssetsField
  • GD
  • Image
  • Image_Cached
  • TarballArchive
  • Upload
  • Upload_Validator

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 Folder record. 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
Extended by ViewableData implements IteratorAggregate
Extended by DataObject implements DataObjectInterface, i18nEntityProvider
Extended by File

Direct known subclasses

Folder, Image

Indirect known subclasses

Image_Cached

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

Methods summary

public static mixed
# find( String $filename )

Find a File object by the given filename.

Find a File object by the given filename.

Parameters

$filename
String
$filename Matched against the "Name" property.

Returns

mixed
null if not found, File object of found file
public
# Link( mixed $action = null )
public
# RelativeLink( mixed $action = null )
public
# TreeTitle( )
public Integer
# BackLinkTrackingCount( )

Returns

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 DataObject::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 DataObject::onBeforeDelete(), though!

Overrides

DataObject::onBeforeDelete
protected
# onAfterDelete( )

Updates link tracking.

Updates link tracking.

Overrides

DataObject::onAfterDelete
public boolean
# canView( Member $member = null )

Parameters

$member
Member
$member

Returns

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

Overrides

DataObject::canEdit
public boolean
# canCreate( Member $member = null )

Parameters

$member
Member
$member

Returns

boolean

Overrides

DataObject::canCreate
public boolean
# canDelete( Member $member = null )

Parameters

$member
Member
$member

Returns

boolean

Overrides

DataObject::canDelete
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".

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".

Returns

String
public
# CMSThumbnail( )
public String
# Icon( )

Return the relative URL of an icon for the file type, based on the File::appCategory() value. Images are searched for in "sapphire/images/app_icons/".

Return the relative URL of an icon for the file type, based on the File::appCategory() value. Images are searched for in "sapphire/images/app_icons/".

Returns

String
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( )

Make sure the file has a name

Make sure the file has a name

Overrides

DataObject::onBeforeWrite
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)

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)

Overrides

DataObject::onAfterWrite
public
# updateFilesystem( )

Moving the file if appropriate according to updated database content. Throws an Exception if the new file already exists.

Moving the file if appropriate according to updated database content. Throws an Exception if the new file already exists.

Caution: This method should just be called during a DataObject::write() invocation, as it relies on DataObject->isChanged(), which is reset after a DataObject::write() call. Might be called as File->updateFilesystem() from within Folder->updateFilesystem(), so it has to handle both files and folders.

Assumes that the "Filename" property was previously updated, either directly or indirectly. (it might have been influenced by File::setName() or File::setParentID() before).

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( 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 File database record in the same folder. This means "myfile.jpg" might become "myfile-1.jpg".

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 File database record in the same folder. This means "myfile.jpg" might become "myfile-1.jpg".

Does not change the filesystem itself, please use DataObject::write() for this.

Parameters

$name
String
$name
protected
# updateLinks( String $old, String $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.

Parameters

$old
String
$old File path relative to the webroot
$new
String
$new File path relative to the webroot

Uses

SiteTree::rewriteFileURL()
public
# setParentID( mixed $parentID )

Does not change the filesystem itself, please use DataObject::write() for this.

Does not change the filesystem itself, please use DataObject::write() for this.

public string
# getAbsoluteURL( )

Gets the absolute URL accessible through the web.

Gets the absolute URL accessible through the web.

Returns

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

Uses

Director::baseURL()
public
# getLinkedURL( )

Return the last 50 characters of the URL.

Return the last 50 characters of the URL.

Deprecated

2.4
public String
# getFullPath( )

Returns an absolute filesystem path to the file. Use File::getRelativePath() to get the same path relative to the webroot.

Returns an absolute filesystem path to the file. Use File::getRelativePath() to get the same path relative to the webroot.

Returns

String
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 Folder is set ("ParentID" property), defaults to a filename relative to the ASSETS_DIR (usually "assets/").

Returns path relative to webroot. Serves as a "fallback" method to create the "Filename" property if it isn't set. If no Folder is set ("ParentID" property), defaults to a filename relative to the ASSETS_DIR (usually "assets/").

Returns

String
public
# DeleteLink( )
public
# getFilename( )
public
# setFilename( mixed $val )

Does not change the filesystem itself, please use DataObject::write() for this.

Does not change the filesystem itself, please use DataObject::write() for this.

public String
# getExtension( )

Returns the file extension

Returns the file extension

Returns

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").

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").

Examples:

  • "myfile" returns ""
  • "myfile.txt" returns "txt"
  • "myfile.tar.gz" returns "gz"

Parameters

$filename
string
$filename

Returns

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
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
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

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.

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 $allowed_extensions
#

List of allowed file extensions, enforced through File::validate().

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
- If you are running IIS you will need to change assets/web.config

Instructions for the change you need to make are included in a comment in the config file.

List of allowed file extensions, enforced through File::validate().

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 - If you are running IIS you will need to change assets/web.config

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 File::$allowed_extensions will be applied to users with admin privileges as well.

this is true, then restrictions set in $allowed_max_file_size and File::$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, $indexes, $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

Comments

Comment policy: Please use comments for tips and corrections about the described functionality. Comments are moderated, we reserve the right to remove comments that are inappropriate or are no longer relevant.
Use the Silverstripe Forum to ask questions.
blog comments powered by Disqus
SilverStripe 2.4 API Docs API documentation generated by ApiGen 2.8.0