class File extends DataObject implements AssetContainer, Thumbnail, CMSPreviewable, PermissionProvider, Resettable

This class handles the representation of a file on the filesystem within the framework.

Most of the methods also handle the {@link Folder} subclass.

Note: The files are stored in the assets/ directory, but SilverStripe 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

Asset storage

As asset storage is configured separately to any File DataObject records, this class does not make any assumptions about how these records are saved. They could be on a local filesystem, remote filesystem, or a virtual record container (such as in local memory).

The File dataobject simply represents an externally facing view of shared resources within this asset store.

Internally individual files are referenced by a"Filename" parameter, which represents a File, extension, and is optionally prefixed by a list of custom directories. This path is root-agnostic, so it does not automatically have a direct url mapping (even to the site's base directory).

Additionally, individual files may have several versions distinguished by sha1 hash, of which a File DataObject can point to a single one. Files can also be distinguished by variants, which may be resized images or format-shifted documents.

Properties

  • "Title": Optional title of the file (for display purposes only). Defaults to "Name". Note that the Title field of Folder (subclass of File) is linked to Name, so Name and Title will always be the same. -"File": Physical asset backing this DB record. This is a composite DB field with its own list of properties. {see DBFile} for more information
  • "Content": Typically unused, but handy for a textual representation of files, e.g. for fulltext indexing of PDF documents.
  • "ParentID": Points to a {@link Folder} record. Should be in sync with "Filename". A ParentID=0 value points to the "assets/" folder, not the webroot. -"ShowInSearch": True if this file is searchable

Traits

Provides image manipulation functionality.
Allows an object to have extensions applied to it.
A class that can be instantiated or replaced via DI
Provides extensions to this object to integrate it with standard config API methods.
Allows an object to declare a set of custom methods

Constants

CHANGE_NONE

Represents a field that hasn't changed (before === after, thus before == after)

CHANGE_STRICT

Represents a field that has changed type, although not the loosely defined value.

(before !== after && before == after) E.g. change 1 to true or "true" to true, but not true to 0. Value changes are by nature also considered strict changes.

CHANGE_VALUE

Represents a field that has changed the loosely defined value (before != after, thus, before !== after)) E.g. change false to true, but not false to 0

EDIT_ALL

Permission for edit all files

Config options

singular_name string
non_live_permissions array Anyone with CMS access can view draft files
allowed_extensions array
app_categories array
class_for_file_extension Map of file extensions to class type
apply_restrictions_to_admin bool
update_filesystem boolean
file_types string[] A list of file extensions and a description of what type of file they represent

Properties

bool $destroyed from DataObject
int $ID ID of the DataObject, 0 if the DataObject doesn't exist in database. from DataObject
int $OldID ID of object, if deleted from DataObject
string $Title Title of the file
string $ClassName Class name of the DataObject from DataObject
string $LastEdited Date and time of DataObject's last modification. from DataObject
string $Created Date and time of DataObject creation. from DataObject
string $ObsoleteClassName If ClassName no longer exists this will be set to the legacy value from DataObject
string $Name Basename of the file
string $Filename Full filename of this file
DBFile $File asset stored behind this File record
string $Content
string $ShowInSearch Boolean that indicates if file is shown in search. Doesn't apply to Folders
int $ParentID ID of parent File/Folder
int $OwnerID ID of Member who owns the file

Methods

mixed
__call(string $method, array $arguments)

Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located

bool
hasMethod(string $method)

Return TRUE if a method exists on this object

array
allMethodNames(bool $custom = false)

Return the names of all the methods available on this object

static bool
add_extension(string $classOrExtension, string $extension = null)

Add an extension to a specific class.

static 
remove_extension(string $extension)

Remove an extension from a class.

static array
get_extensions(string $class = null, bool $includeArgumentString = false)

No description

static array|null
get_extra_config_sources(string $class = null)

Get extra config sources for this class

static bool
has_extension(string $classOrExtension, string $requiredExtension = null, boolean $strict = false)

Return TRUE if a class has a specified extension.

array
invokeWithExtensions(string $method, mixed $arguments)

Calls a method if available on both this object and all applied {@link Extensions}, and then attempts to merge all results into an array

array
extend(string $method, mixed $arguments)

Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed

Extension|null
getExtensionInstance(string $extension)

Get an extension instance attached to this object by name.

bool
hasExtension(string $extension)

Returns TRUE if this object instance has a specific extension applied in {@link $extension_instances}. Extension instances are initialized at constructor time, meaning if you use {@link add_extension()} afterwards, the added extension will just be added to new instances of the extended class. Use the static method {@link has_extension()} to check if a class (not an instance) has a specific extension.

getExtensionInstances()

Get all extension instances for this specific object instance.

static Injectable
create(array $args)

An implementation of the factory method, allows you to create an instance of a class

static Injectable
singleton(string $class = null)

Creates a class instance by the "singleton" design pattern.

static Config_ForClass
config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .

mixed
stat(string $name) deprecated

Get inherited config value

mixed
uninherited(string $name)

Gets the uninherited value for the given config option

$this
set_stat(string $name, mixed $value) deprecated

Update the config value for a given property

__construct(array|null $record = null, boolean $isSingleton = false, array $queryParams = array())

Construct a new DataObject.

bool
__isset(string $property)

Check if a field exists on this object or its failover.

mixed
__get(string $property)

Get the value of a property/field on this object. This will check if a method called get{$property} exists, then check if a field is available using {@link ViewableData::getField()}, then fall back on a failover object.

__set(string $property, mixed $value)

Set a property/field on this object. This will check for the existence of a method called set{$property}, then use the {@link ViewableData::setField()} method.

setFailover(ViewableData $failover)

Set a failover object to attempt to get data from if it is not present on this object.

getFailover()

Get the current failover object if set

bool
hasField(string $field)

Returns true if the given field exists in a database column on any of the objects tables and optionally look up a dynamic getter with get().

mixed
getField(string $field)

Gets the value of a field.

$this
setField(string $fieldName, mixed $val)

Set the value of the field Called by {@link __set()} and any setFieldName() methods you might create.

defineMethods()

Adds methods from the extensions.

customise(array|ViewableData $data)

Merge some arbitrary data in with this object. This method returns a {@link ViewableData_Customised} instance with references to both this and the new custom data.

bool
exists()

A file only exists if the file_exists() and is in the DB as a record

string
__toString()

No description

getCustomisedObj()

No description

setCustomisedObj(ViewableData $object)

No description

string
castingHelper(string $field)

Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field on this object. This helper will be a subclass of DBField.

string
castingClass(string $field)

Get the class name a field on this object will be casted to.

string
escapeTypeForField(string $field)

Return the string-format type for the given field.

renderWith(string|array|SSViewer $template, array $customFields = null)

Render this object into the template, and get the result as a string. You can pass one of the following as the $template parameter: - a template name (e.g. Page) - an array of possible template names - the first valid one will be used - an SSViewer instance

Object|DBField
obj(string $fieldName, array $arguments = [], bool $cache = false, string $cacheName = null)

Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified.

Object|DBField
cachedCall(string $field, array $arguments = [], string $identifier = null)

A simple wrapper around {@link ViewableData::obj()} that automatically caches the result so it can be used again without re-running the method.

bool
hasValue(string $field, array $arguments = null, bool $cache = true)

Returns true if the given method/parameter has a value (Uses the DBField::hasValue if the parameter is a database field)

string
XML_val(string $field, array $arguments = [], bool $cache = false)

Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template.

array
getXMLValues(array $fields)

Get an array of XML-escaped values by field name

getIterator()

Return a single-item iterator so you can iterate over the fields of a single record.

array
getViewerTemplates(string $suffix = '')

Find appropriate templates for SSViewer to use to render this object

Me()

When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself.

string
ThemeDir() deprecated

Return the directory if the current active theme (relative to the site root).

string
CSSClasses(string $stopAtClass = self::class)

Get part of the current classes ancestry to be used as a CSS class.

Debug()

Return debug information about this object that can be rendered into a template

getSchema()

Get schema object

destroy()

Destroy all of this objects dependant objects and local caches.

duplicate(bool $doWrite = true, array|null|false $relations = null)

Create a duplicate of this node. Can duplicate many_many relations

string
getObsoleteClassName()

Return obsolete class name, if this is no longer a valid class

string
getClassName()

Gets name of this class

$this
setClassName(string $className)

Set the ClassName attribute. {@link $class} is also updated.

newClassInstance(string $newClassName)

Create a new instance of a different class from this object's record.

boolean
isEmpty()

Returns TRUE if all values (other than "ID") are considered empty (by weak boolean comparison).

string
i18n_pluralise(string $count)

Pluralise this item given a specific count.

string
singular_name()

Get the user friendly singular name of this DataObject.

string
i18n_singular_name()

Get the translated user friendly singular name of this DataObject same as singular_name() but runs it through the translating function

string
plural_name()

Get the user friendly plural name of this DataObject If the name is not defined (by renaming $plural_name in the subclass), this returns a pluralised version of the class name.

string
i18n_plural_name()

Get the translated user friendly plural name of this DataObject Same as plural_name but runs it through the translation function Translation string is in the form: $this->class.PLURALNAME Example: Page.PLURALNAME

string
getTitle()

Standard implementation of a title/label for a specific record. Tries to find properties 'Title' or 'Name', and falls back to the 'ID'. Useful to provide user-friendly identification of a record, e.g. in errormessages or UI-selections.

data()

Returns the associated database record - in this case, the object itself.

array
toMap()

Convert this object to a map.

array
getQueriedDatabaseFields()

Return all currently fetched database fields.

update(array $data)

Update a number of fields on this object, given a map of the desired changes.

castedUpdate(array $data)

Pass changes as a map, and try to get automatic casting for these fields.

Boolean
merge(DataObject $rightObj, string $priority = 'right', bool $includeRelations = true, bool $overwriteWithEmpty = false)

Merges data and relations from another object of same class, without conflict resolution. Allows to specify which dataset takes priority in case its not empty.

$this
forceChange()

Forces the record to think that all its data has changed.

validate()

No description

doValidate()

Public accessor for {see DataObject::validate()}

findCascadeDeletes(bool $recursive = true, ArrayList $list = null)

Find all objects that will be cascade deleted if this object is deleted

populateDefaults()

Load the default values in from the self::$defaults array.

write(boolean $showDebug = false, boolean $forceInsert = false, boolean $forceWrite = false, boolean|array $writeComponents = false)

Writes all changes to this object to the database.

writeRelations()

Writes cached relation lists to the database, if possible

writeComponents(bool $recursive = false, array $skip = [])

Write the cached components to the database. Cached components could refer to two different instances of the same record.

delete()

Delete this data object.

static 
delete_by_id(string $className, int $id)

Delete the record with the given ID.

array
getClassAncestry()

Get the class ancestry, including the current class name.

getComponent(string $componentName)

Return a unary component object from a one to one relationship, as a DataObject.

$this
setComponent(string $componentName, DataObject|null $item)

Assign an item to the given component

getComponents(string $componentName, int|array $id = null)

Returns a one-to-many relation as a HasManyList

string
getRelationClass(string $relationName)

Find the foreign class of a relation on this DataObject, regardless of the relation type.

string
getRelationType(string $component)

Given a relation name, determine the relation type

inferReciprocalComponent(string $remoteClass, string $remoteRelation)

Given a relation declared on a remote class, generate a substitute component for the opposite side of the relation.

getManyManyComponents(string $componentName, int|array $id = null)

Returns a many-to-many component, as a ManyManyList.

string|array
hasOne()

Return the class of a one-to-one component. If $component is null, return all of the one-to-one components and their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.

string|array
belongsTo(bool $classOnly = true)

Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and their class name will be returned.

string|array|false
hasMany(bool $classOnly = true)

Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many relationships and their classes will be returned.

array|null
manyManyExtraFields()

Return the many-to-many extra fields specification.

array|null
manyMany()

Return information about a many-to-many component.

array|false
database_extensions(string $class)

This returns an array (if it exists) describing the database extensions that are required, or false if none

getDefaultSearchContext()

Generates a SearchContext to be used for building and processing a generic search form for properties on this object.

scaffoldSearchFields(array $_params = null)

Determine which properties on the DataObject are searchable, and map them to their default {@link FormField} representations. Used for scaffolding a searchform for {@link ModelAdmin}.

scaffoldFormFields(array $_params = null)

Scaffold a simple edit form for all properties on this dataobject, based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.

getCMSFields()

List of basic content editable file fields.

getCMSActions()

need to be overload by solid dataobject, so that the customised actions of that dataobject, including that dataobject's extensions customised actions could be added to the EditForm.

getFrontEndFields(array $params = null)

Used for simple frontend forms without relation editing or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()} by default. To customize, either overload this method in your subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.

array
getChangedFields(boolean|array $databaseFieldsOnly = false, int $changeLevel = self::CHANGE_STRICT)

Return the fields that have changed since the last write.

boolean
isChanged(string $fieldName = null, int $changeLevel = self::CHANGE_STRICT)

Uses {@link getChangedFields()} to determine if fields have been changed since loading them from the database.

$this
setCastedField(string $fieldName, mixed $value)

Set the value of the field, using a casting object.

boolean
hasDatabaseField(string $field)

Returns true if the given field exists as a database column

boolean
can(string $perm, Member $member = null, array $context = array())

Returns true if the member is allowed to do the given action.

boolean|null
extendedCan(string $methodName, Member|int $member, array $context = array())

Process tri-state responses from permission-alterting extensions. The extensions are expected to return one of three values:

boolean
canView(Member $member = null)

No description

boolean
canEdit(Member $member = null)

Check if this file can be modified

boolean
canDelete(Member $member = null)

Check if this file can be deleted

boolean
canCreate(Member $member = null, array $context = array())

Check if a file can be created

string
debug()

Debugging used by Debug::show()

dbObject(string $fieldName)

Return the DBField object that represents the given field.

mixed
relObject(string $fieldPath)

Traverses to a DBField referenced by relationships between data objects.

mixed
relField(string $fieldName)

Traverses to a field referenced by relationships between data objects, returning the value The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)

string
getReverseAssociation(string $className)

Temporary hack to return an association name, based on class, to get around the mangle of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.

static DataList
get(string $callerClass = null, string|array $filter = "", string|array $sort = "", string $join = "", string|array $limit = null, string $containerClass = DataList::class)

Return all objects matching the filter sub-classes are automatically selected and included

static DataObject|null
get_one(string|null $callerClass = null, string|array $filter = "", boolean $cache = true, string $orderBy = "")

Return the first item matching the given query.

flushCache(boolean $persistent = true)

Flush the cached results for all relations (has_one, has_many, many_many) Also clears any cached aggregate data.

static 
flush_and_destroy_cache()

Flush the get_one global cache and destroy associated objects.

static 
reset()

Reset all global caches associated with DataObject.

static DataObject
get_by_id(string|int $classOrID, int|bool $idOrCache = null, boolean $cache = true)

Return the given element, searching by ID.

string
baseTable()

Get the name of the base table for this object

string
baseClass()

Get the base class for this object

array
getSourceQueryParams()

No description

array
getInheritableQueryParams()

Get list of parameters that should be inherited to relations on this object

setSourceQueryParams(array $array)

No description

setSourceQueryParam(string $key, string $value)

No description

string
getSourceQueryParam(string $key)

No description

requireTable()

Check the database schema and update it as necessary.

requireDefaultRecords()

Add default records to database. This function is called whenever the database is built, after the database tables have all been created. Overload this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().

array
searchableFields()

Get the default searchable fields for this object, as defined in the $searchable_fields list. If searchable fields are not defined on the data object, uses a default selection of summary fields.

array
fieldLabels(boolean $includerelations = true)

Get any user defined searchable fields labels that exist. Allows overriding of default field names in the form interface actually presented to the user.

string
fieldLabel(string $name)

Get a human-readable label for a single field, see {@link fieldLabels()} for more details.

array
summaryFields()

Get the default summary fields for this object.

array
defaultSearchFilters()

Defines a default list of filters for the search context.

boolean
isInDB()

No description

static 
disable_subclass_access()

Temporarily disable subclass access in data object qeur

static 
enable_subclass_access()

No description

array
provideI18nEntities()

Returns the list of provided translations for this object.

getJoin()

If selected through a many_many through relation, this is the instance of the joined record

$this
setJoin(DataObject $object, string $alias = null)

Set joining object

findRelatedObjects(string $source, bool $recursive = true, ArrayList $list = null)

Find objects in the given relationships, merging them into the given list

mergeRelatedObjects(ArrayList $list, mixed $items)

Helper method to merge owned/owning items into a list.

$this
setAllowGeneration(bool $allow)

Set whether image resizes are allowed

bool
getAllowGeneration()

Check if resizes are allowed

existingOnly()

Return clone of self which promises to only return existing thumbnails

string
getString()

No description

resource
getStream()

No description

string
getURL(bool $grant = true)

Gets the URL of this file

string
getAbsoluteURL()

Gets the URL of this file

array|null
getMetaData()

Get metadata for this file

string
getMimeType()

Get mime type

int
getAbsoluteSize()

Return file size in bytes.

string
getFilename()

Get value of filename

string
getHash()

Get value of hash

string
getVariant()

Get value of variant

bool
getIsImage()

Determine if a valid non-empty image exists behind this asset

Pad(int $width, int $height, string $backgroundColor = 'FFFFFF', int $transparencyPercent)

Fit image to specified dimensions and fill leftover space with a solid colour (default white). Use in templates with $Pad.

Resampled()

Forces the image to be resampled, if possible

updateURL(string $url)

Update the url to point to a resampled version if forcing

ResizedImage(int $width, int $height)

Generate a resized copy of this image with the given width & height.

Fit(int $width, int $height)

Scale image proportionally to fit within the specified bounds

FitMax(int $width, int $height)

Proportionally scale down this image if it is wider or taller than the specified dimensions.

ScaleWidth(int $width)

Scale image proportionally by width. Use in templates with $ScaleWidth.

ScaleMaxWidth(int $width)

Proportionally scale down this image if it is wider than the specified width.

ScaleHeight(int $height)

Scale image proportionally by height. Use in templates with $ScaleHeight.

ScaleMaxHeight(int $height)

Proportionally scale down this image if it is taller than the specified height.

CropWidth(int $width)

Crop image on X axis if it exceeds specified width. Retain height.

CropHeight(int $height)

Crop image on Y axis if it exceeds specified height. Retain width.

FillMax(int $width, int $height)

Crop this image to the aspect ratio defined by the specified width and height, then scale down the image to those dimensions if it exceeds them.

Fill(int $width, int $height)

Resize and crop image to fill specified dimensions.

Quality(int $quality)

Set the quality of the resampled image

CMSThumbnail()

Default CMS thumbnail

StripThumbnail()

Generates a thumbnail for use in the gridfield view

PreviewThumbnail()

Get preview for this file

Thumbnail(int $width, int $height)

Default thumbnail generation for Images

ThumbnailIcon(int $width, int $height)

Thumbnail generation for all file types.

IconTag()

Get HTML for img containing the icon for this file

string
ThumbnailURL(int $width, int $height)

Get URL to thumbnail of the given size.

string
getIcon()

Return the relative URL of an icon for the file type, based on the {@link appCategory()} value.

getImageBackend()

Get Image_Backend instance for this image

$this
setImageBackend(Image_Backend $backend)

No description

int
getWidth()

Get the width of this image.

int
getHeight()

Get the height of this image.

int
getOrientation()

Get the orientation of this image.

boolean
isSize(int $width, int $height)

Determine if this image is of the specified size

boolean
isWidth(int $width)

Determine if this image is of the specified width

boolean
isHeight(int $height)

Determine if this image is of the specified width

manipulateImage(string $variant, callable $callback)

Wrapper for manipulate that passes in and stores Image_Backend objects instead of tuples

manipulate(string $variant, callable $callback)

Generate a new DBFile instance using the given callback if it hasn't been created yet, or return the existing one if it has.

string
variantName($format, $arg = null)

Name a variant based on a format with arbitrary parameters

array|null
variantParts($variantName)

Reverses {@link variantName()}.

static 
get_shortcodes()

No description

static File
find(string $filename)

Find a File object by the given filename.

string
Link()

Just an alias function to keep a consistent API with SiteTree

RelativeLink() deprecated

No description

string
AbsoluteLink()

Just an alias function to keep a consistent API with SiteTree

string
getTreeTitle()

No description

string
getStatusTitle()

Get title for current file status

static string
get_app_category(string $ext)

Returns a category based on the file extension.

static array
get_category_extensions(array|string $categories)

For a category or list of categories, get the list of file extensions

string
appCategory()

Returns a category based on the file extension.

onAfterUpload()

Should be called after the file was uploaded

onAfterRevertToLive()

No description

bool
updateFilesystem()

This will check if the parent record and/or name do not match the name on the underlying DBFile record, and if so, copy this file to the new location, and update the record to point to this new file.

true|null
collateDescendants(string $condition, array $collator)

Collate selected descendants of this page.

string
getSourceURL(bool $grant = true)

Get URL, but without resampling.

string
generateFilename()

Get expected value of Filename tuple value. Will be used to trigger a file move on draft stage.

string
renameFile(string $newName)

Rename this file.

string
copyFile(string $newName)

Copy to new filename.

$this
setFilename(string $filename)

Update the ParentID and Name for the given filename.

string
getExtension()

Returns the file extension

static string
get_file_extension(string $filename)

Gets the extension of a filepath or filename, by stripping away everything before the last "dot".

static string
get_icon_for_extension(string $extension)

Given an extension, determine the icon that should be used

string
getFileType()

Return the type of file for the given extension on the current file name.

static string
get_file_type(string $filename)

Get descriptive type of file based on filename

string|false
getSize()

Returns the size of the file type in an appropriate format.

static string
format_size(int $size)

Formats a file size (eg: (int)42 becomes string '42 bytes')

static int
ini2bytes(string $iniValue) deprecated

Convert a php.ini value (eg: 512M) to bytes

static String
get_class_for_file_extension(String $ext)

Maps a {@link File} subclass to a specific extension.

static 
set_class_for_file_extension(String|array $exts, String $class)

See {@link get_class_for_file_extension()}.

array
setFromLocalFile(string $path, string $filename = null, string $hash = null, string $variant = null, array $config = array())

Assign a local file to the backend.

array
setFromStream(resource $stream, string $filename, string $hash = null, string $variant = null, array $config = array())

Assign a stream to the backend

array
setFromString(string $data, string $filename, string $hash = null, string $variant = null, array $config = array())

Assign a set of data to the backend

string
forTemplate()

Return a html5 tag of the appropriate for this file (normally img or a)

string
getTag()

Return a html5 tag of the appropriate for this file (normally img or a)

BackLinkTracking()

Get the back-link tracking objects that link to this file via HTML fields

int
BackLinkTrackingCount()

Count of backlinks Note: Doesn't filter broken records

static string
join_paths($part = null)

Joins one or more segments together to build a Filename identifier.

bool
deleteFile()

Delete a file (and all variants).

string
getVisibility()

Determine visibility of the given file

publishFile()

Publicly expose the file (and all variants) identified by the given filename and hash {see AssetStore::publish}

protectFile()

Protect a file (and all variants) from public access, identified by the given filename and hash.

grantFile()

Ensures that access to the specified protected file is granted for the current user.

revokeFile()

Revoke access to the given file for the current user.

bool
canViewFile()

Check if the current user can view the given file.

string
CMSEditLink()

No description

string
PreviewLink(string $action = null)

Determine the preview link, if available, for this object.

providePermissions()

Return a map of permission codes to add to the dropdown shown in the Security section of the CMS.

static array
getAllowedExtensions()

Get the list of globally allowed file extensions for file uploads.

File
Parent()

Returns parent File

Member
Owner()

Returns Member object of file owner.

Details

in CustomMethods at line 50
mixed __call(string $method, array $arguments)

Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located

You can add extra methods to a class using {@link Extensions}, {@link Object::createMethod()} or {@link Object::addWrapperMethod()}

Parameters

string $method
array $arguments

Return Value

mixed

Exceptions

BadMethodCallException

in CustomMethods at line 144
bool hasMethod(string $method)

Return TRUE if a method exists on this object

This should be used rather than PHP's inbuild method_exists() as it takes into account methods added via extensions

Parameters

string $method

Return Value

bool

in CustomMethods at line 172
array allMethodNames(bool $custom = false)

Return the names of all the methods available on this object

Parameters

bool $custom include methods added dynamically at runtime

Return Value

array Map of method names with lowercase keys

in Extensible at line 163
static bool add_extension(string $classOrExtension, string $extension = null)

Add an extension to a specific class.

The preferred method for adding extensions is through YAML config, since it avoids autoloading the class, and is easier to override in more specific configurations.

As an alternative, extensions can be added to a specific class directly in the {@link Object::$extensions} array. See {@link SiteTree::$extensions} for examples. Keep in mind that the extension will only be applied to new instances, not existing ones (including all instances created through {@link singleton()}).

Parameters

string $classOrExtension Class that should be extended - has to be a subclass of {@link Object}
string $extension Subclass of {@link Extension} with optional parameters as a string, e.g. "Versioned" or "Translatable('Param')"

Return Value

bool Flag if the extension was added

See also

http://doc.silverstripe.org/framework/en/trunk/reference/dataextension

in Extensible at line 224
static remove_extension(string $extension)

Remove an extension from a class.

Note: This will not remove extensions from parent classes, and must be called directly on the class assigned the extension.

Keep in mind that this won't revert any datamodel additions of the extension at runtime, unless its used before the schema building kicks in (in your _config.php). Doesn't remove the extension from any {@link Object} instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through {@link singleton()} to avoid side-effects from stale extension information.

Parameters

string $extension class name of an {@link Extension} subclass, without parameters

in Extensible at line 264
static array get_extensions(string $class = null, bool $includeArgumentString = false)

Parameters

string $class If omitted, will get extensions for the current class
bool $includeArgumentString Include the argument string in the return array, FALSE would return array("Versioned"), TRUE returns array("Versioned('Stage','Live')").

Return Value

array Numeric array of either {@link DataExtension} class names, or eval'ed class name strings with constructor arguments.

in Extensible at line 298
static array|null get_extra_config_sources(string $class = null)

Get extra config sources for this class

Parameters

string $class Name of class. If left null will return for the current class

Return Value

array|null

in Extensible at line 359
static bool has_extension(string $classOrExtension, string $requiredExtension = null, boolean $strict = false)

Return TRUE if a class has a specified extension.

This supports backwards-compatible format (static Object::has_extension($requiredExtension)) and new format ($object->has_extension($class, $requiredExtension))

Parameters

string $classOrExtension Class to check extension for, or the extension name to check if the second argument is null.
string $requiredExtension If the first argument is the parent class, this is the extension to check. If left null, the first parameter will be treated as the extension.
boolean $strict if the extension has to match the required extension and not be a subclass

Return Value

bool Flag if the extension exists

in Extensible at line 395
array invokeWithExtensions(string $method, mixed $arguments)

Calls a method if available on both this object and all applied {@link Extensions}, and then attempts to merge all results into an array

Parameters

string $method the method name to call
mixed $arguments List of arguments

Return Value

array List of results with nulls filtered out

in Extensible at line 424
array extend(string $method, mixed $arguments)

Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed

Currently returns an array, with an index resulting every time the function is called. Only adds returns if they're not NULL, to avoid bogus results from methods just defined on the parent extension. This is important for permission-checks through extend, as they use min() to determine if any of the returns is FALSE. As min() doesn't do type checking, an included NULL return would fail the permission checks.

The extension methods are defined during {@link __construct()} in {@link defineMethods()}.

Parameters

string $method the name of the method to call on each extension
mixed $arguments &...$arguments

Return Value

array

in Extensible at line 465
Extension|null getExtensionInstance(string $extension)

Get an extension instance attached to this object by name.

Parameters

string $extension

Return Value

Extension|null

in Extensible at line 494
bool hasExtension(string $extension)

Returns TRUE if this object instance has a specific extension applied in {@link $extension_instances}. Extension instances are initialized at constructor time, meaning if you use {@link add_extension()} afterwards, the added extension will just be added to new instances of the extended class. Use the static method {@link has_extension()} to check if a class (not an instance) has a specific extension.

Caution: Don't use singleton()->hasExtension() as it will give you inconsistent results based on when the singleton was first accessed.

Parameters

string $extension Classname of an {@link Extension} subclass without parameters

Return Value

bool

in Extensible at line 508
Extension[] getExtensionInstances()

Get all extension instances for this specific object instance.

See {@link get_extensions()} to get all applied extension classes for this class (not the instance).

This method also provides lazy-population of the extension_instances property.

Return Value

Extension[] Map of {@link DataExtension} instances, keyed by classname.

in Injectable at line 26
static Injectable create(array $args)

An implementation of the factory method, allows you to create an instance of a class

This method will defer class substitution to the Injector API, which can be customised via the Config API to declare substitution classes.

This can be called in one of two ways - either calling via the class directly, or calling on Object and passing the class name as the first parameter. The following are equivalent: $list = DataList::create('SiteTree'); $list = SiteTree::get();

Parameters

array $args

Return Value

Injectable

in Injectable at line 43
static Injectable singleton(string $class = null)

Creates a class instance by the "singleton" design pattern.

It will always return the same instance for this class, which can be used for performance reasons and as a simple way to access instance methods which don't rely on instance data (e.g. the custom SilverStripe static handling).

Parameters

string $class Optional classname to create, if the called class should not be used

Return Value

Injectable The singleton instance

in Configurable at line 20
static Config_ForClass config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .

....).

Return Value

Config_ForClass

in Configurable at line 32
mixed stat(string $name) deprecated

deprecated 5.0 Use ->config()->get() instead

Get inherited config value

Parameters

string $name

Return Value

mixed

in Configurable at line 44
mixed uninherited(string $name)

Gets the uninherited value for the given config option

Parameters

string $name

Return Value

mixed

in Configurable at line 57
$this set_stat(string $name, mixed $value) deprecated

deprecated 5.0 Use ->config()->set() instead

Update the config value for a given property

Parameters

string $name
mixed $value

Return Value

$this

in DataObject at line 327
__construct(array|null $record = null, boolean $isSingleton = false, array $queryParams = array())

Construct a new DataObject.

Parameters

array|null $record Used internally for rehydrating an object from database content. Bypasses setters on this class, and hence should not be used for populating data on new records.
boolean $isSingleton This this to true if this is a singleton() object, a stub for calling methods. Singletons don't have their defaults set.
array $queryParams List of DataQuery params necessary to lazy load, or load related objects.

in ViewableData at line 106
bool __isset(string $property)

Check if a field exists on this object or its failover.

Note that, unlike the core isset() implementation, this will return true if the property is defined and set to null.

Parameters

string $property

Return Value

bool

in ViewableData at line 129
mixed __get(string $property)

Get the value of a property/field on this object. This will check if a method called get{$property} exists, then check if a field is available using {@link ViewableData::getField()}, then fall back on a failover object.

Parameters

string $property

Return Value

mixed

in ViewableData at line 152
__set(string $property, mixed $value)

Set a property/field on this object. This will check for the existence of a method called set{$property}, then use the {@link ViewableData::setField()} method.

Parameters

string $property
mixed $value

in ViewableData at line 167
setFailover(ViewableData $failover)

Set a failover object to attempt to get data from if it is not present on this object.

Parameters

ViewableData $failover

in ViewableData at line 183
ViewableData|null getFailover()

Get the current failover object if set

Return Value

ViewableData|null

in DataObject at line 2827
bool hasField(string $field)

Returns true if the given field exists in a database column on any of the objects tables and optionally look up a dynamic getter with get().

Parameters

string $field

Return Value

bool

in DataObject at line 2470
mixed getField(string $field)

Gets the value of a field.

Called by {@link __get()} and any getFieldName() methods you might create.

Parameters

string $field

Return Value

mixed

in DataObject at line 2688
$this setField(string $fieldName, mixed $val)

Set the value of the field Called by {@link __set()} and any setFieldName() methods you might create.

Parameters

string $fieldName Name of the field
mixed $val New field value

Return Value

$this

in DataObject at line 717
defineMethods()

Adds methods from the extensions.

Called by Object::__construct() once per class.

in ViewableData at line 258
ViewableData_Customised customise(array|ViewableData $data)

Merge some arbitrary data in with this object. This method returns a {@link ViewableData_Customised} instance with references to both this and the new custom data.

Note that any fields you specify will take precedence over the fields on this object.

Parameters

array|ViewableData $data

Return Value

ViewableData_Customised

at line 285
bool exists()

A file only exists if the file_exists() and is in the DB as a record

Use $file->isInDB() to only check for a DB record Use $file->File->exists() to only check if the asset exists

Return Value

bool

in ViewableData at line 289
string __toString()

Return Value

string the class name

in ViewableData at line 297
ViewableData getCustomisedObj()

Return Value

ViewableData

in ViewableData at line 305
setCustomisedObj(ViewableData $object)

Parameters

ViewableData $object

in DataObject at line 2798
string castingHelper(string $field)

Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field on this object. This helper will be a subclass of DBField.

Parameters

string $field

Return Value

string Casting helper As a constructor pattern, and may include arguments.

Exceptions

Exception

in ViewableData at line 352
string castingClass(string $field)

Get the class name a field on this object will be casted to.

Parameters

string $field

Return Value

string

in ViewableData at line 365
string escapeTypeForField(string $field)

Return the string-format type for the given field.

Parameters

string $field

Return Value

string 'xml'|'raw'

in ViewableData at line 389
DBHTMLText renderWith(string|array|SSViewer $template, array $customFields = null)

Render this object into the template, and get the result as a string. You can pass one of the following as the $template parameter: - a template name (e.g. Page) - an array of possible template names - the first valid one will be used - an SSViewer instance

Parameters

string|array|SSViewer $template the template to render into
array $customFields fields to customise() the object with before rendering

Return Value

DBHTMLText

in ViewableData at line 471
Object|DBField obj(string $fieldName, array $arguments = [], bool $cache = false, string $cacheName = null)

Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified.

Parameters

string $fieldName
array $arguments
bool $cache Cache this object
string $cacheName a custom cache name

Return Value

Object|DBField

in ViewableData at line 516
Object|DBField cachedCall(string $field, array $arguments = [], string $identifier = null)

A simple wrapper around {@link ViewableData::obj()} that automatically caches the result so it can be used again without re-running the method.

Parameters

string $field
array $arguments
string $identifier an optional custom cache identifier

Return Value

Object|DBField

in DataObject at line 4091
bool hasValue(string $field, array $arguments = null, bool $cache = true)

Returns true if the given method/parameter has a value (Uses the DBField::hasValue if the parameter is a database field)

Parameters

string $field
array $arguments
bool $cache

Return Value

bool

in ViewableData at line 545
string XML_val(string $field, array $arguments = [], bool $cache = false)

Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template.

Parameters

string $field
array $arguments
bool $cache

Return Value

string

in ViewableData at line 558
array getXMLValues(array $fields)

Get an array of XML-escaped values by field name

Parameters

array $fields an array of field names

Return Value

array

in ViewableData at line 579
ArrayIterator getIterator()

Return a single-item iterator so you can iterate over the fields of a single record.

This is useful so you can use a single record inside a <% control %> block in a template - and then use to access individual fields on this object.

Return Value

ArrayIterator

in DataObject at line 2458
array getViewerTemplates(string $suffix = '')

Find appropriate templates for SSViewer to use to render this object

Parameters

string $suffix

Return Value

array

in ViewableData at line 603
ViewableData Me()

When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself.

Return Value

ViewableData

in ViewableData at line 620
string ThemeDir() deprecated

deprecated 4.0.0:5.0.0 Use $resourcePath or $resourceURL template helpers instead

Return the directory if the current active theme (relative to the site root).

This method is useful for things such as accessing theme images from your template without hardcoding the theme page - e.g. .

This method should only be used when a theme is currently active. However, it will fall over to the current project directory.

Return Value

string URL to the current theme

in ViewableData at line 647
string CSSClasses(string $stopAtClass = self::class)

Get part of the current classes ancestry to be used as a CSS class.

This method returns an escaped string of CSS classes representing the current classes ancestry until it hits a stop point - e.g. "Page DataObject ViewableData".

Parameters

string $stopAtClass the class to stop at (default: ViewableData)

Return Value

string

in ViewableData at line 676
ViewableData_Debugger Debug()

Return debug information about this object that can be rendered into a template

Return Value

ViewableData_Debugger

in DataObject at line 312
static DataObjectSchema getSchema()

Get schema object

Return Value

DataObjectSchema

in DataObject at line 408
destroy()

Destroy all of this objects dependant objects and local caches.

You'll need to call this to get the memory of an object that has components or extensions freed.

in DataObject at line 425
DataObject duplicate(bool $doWrite = true, array|null|false $relations = null)

Create a duplicate of this node. Can duplicate many_many relations

Parameters

bool $doWrite Perform a write() operation before returning the object. If this is true, it will create the duplicate in the database.
array|null|false $relations List of relations to duplicate. Will default to cascade_duplicates if null. Set to 'false' to force none. Set to specific array of names to duplicate to override these. Note: If using versioned, this will additionally failover to owns config.

Return Value

DataObject A duplicate of this node. The exact type will be the type of this node.

in DataObject at line 631
string getObsoleteClassName()

Return obsolete class name, if this is no longer a valid class

Return Value

string

in DataObject at line 645
string getClassName()

Gets name of this class

Return Value

string

in DataObject at line 664
$this setClassName(string $className)

Set the ClassName attribute. {@link $class} is also updated.

Warning: This will produce an inconsistent record, as the object instance will not automatically switch to the new subclass. Please use {@link newClassInstance()} for this purpose, or destroy and reinstanciate the record.

Parameters

string $className The new ClassName attribute (a subclass of {@link DataObject})

Return Value

$this

in DataObject at line 692
DataObject newClassInstance(string $newClassName)

Create a new instance of a different class from this object's record.

This is useful when dynamically changing the type of an instance. Specifically, it ensures that the instance of the class is a match for the className of the record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName} property manually before calling this method, as it will confuse change detection.

If the new class is different to the original class, defaults are populated again because this will only occur automatically on instantiation of a DataObject if there is no record, or the record has no ID. In this case, we do have an ID but we still need to repopulate the defaults.

Parameters

string $newClassName The name of the new class

Return Value

DataObject The new instance of the new class, The exact type will be of the class name provided.

in DataObject at line 766
boolean isEmpty()

Returns TRUE if all values (other than "ID") are considered empty (by weak boolean comparison).

Return Value

boolean

in DataObject at line 794
string i18n_pluralise(string $count)

Pluralise this item given a specific count.

E.g. "0 Pages", "1 File", "3 Images"

Parameters

string $count

Return Value

string

in DataObject at line 811
string singular_name()

Get the user friendly singular name of this DataObject.

If the name is not defined (by redefining $singular_name in the subclass), this returns the class name.

Return Value

string User friendly singular name of this DataObject

in DataObject at line 835
string i18n_singular_name()

Get the translated user friendly singular name of this DataObject same as singular_name() but runs it through the translating function

Translating string is in the form: $this->class.SINGULARNAME Example: Page.SINGULARNAME

Return Value

string User friendly translated singular name of this DataObject

in DataObject at line 847
string plural_name()

Get the user friendly plural name of this DataObject If the name is not defined (by renaming $plural_name in the subclass), this returns a pluralised version of the class name.

Return Value

string User friendly plural name of this DataObject

in DataObject at line 870
string i18n_plural_name()

Get the translated user friendly plural name of this DataObject Same as plural_name but runs it through the translation function Translation string is in the form: $this->class.PLURALNAME Example: Page.PLURALNAME

Return Value

string User friendly translated plural name of this DataObject

in DataObject at line 892
string getTitle()

Standard implementation of a title/label for a specific record. Tries to find properties 'Title' or 'Name', and falls back to the 'ID'. Useful to provide user-friendly identification of a record, e.g. in errormessages or UI-selections.

Overload this method to have a more specialized implementation, e.g. for an Address record this could be: function getTitle() { return "{$this->StreetNumber} {$this->StreetName} {$this->City}"; }

Return Value

string

in DataObject at line 911
DataObject data()

Returns the associated database record - in this case, the object itself.

This is included so that you can call $dataOrController->data() and get a DataObject all the time.

Return Value

DataObject Associated database record

in DataObject at line 921
array toMap()

Convert this object to a map.

Return Value

array The data as a map.

in DataObject at line 935
array getQueriedDatabaseFields()

Return all currently fetched database fields.

This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields. Obviously, this makes it a lot faster.

Return Value

array The data as a map.

in DataObject at line 955
DataObject update(array $data)

Update a number of fields on this object, given a map of the desired changes.

The field names can be simple names, or you can use a dot syntax to access $has_one relations. For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".

Doesn't write the main object, but if you use the dot syntax, it will write() the related objects that it alters.

When using this method with user supplied data, it's very important to whitelist the allowed keys.

Parameters

array $data A map of field name to data values to update.

Return Value

DataObject $this

in DataObject at line 1016
DataObject castedUpdate(array $data)

Pass changes as a map, and try to get automatic casting for these fields.

Doesn't write to the database. To write the data, use the write() method.

Parameters

array $data A map of field name to data values to update.

Return Value

DataObject $this

in DataObject at line 1045
Boolean merge(DataObject $rightObj, string $priority = 'right', bool $includeRelations = true, bool $overwriteWithEmpty = false)

Merges data and relations from another object of same class, without conflict resolution. Allows to specify which dataset takes priority in case its not empty.

has_one-relations are just transferred with priority 'right'. has_many and many_many-relations are added regardless of priority.

Caution: has_many/many_many relations are moved rather than duplicated, meaning they are not connected to the merged object any longer. Caution: Just saves updated has_many/many_many relations to the database, doesn't write the updated object itself (just writes the object-properties). Caution: Does not delete the merged object. Caution: Does now overwrite Created date on the original object.

Parameters

DataObject $rightObj
string $priority left|right Determines who wins in case of a conflict (optional)
bool $includeRelations Merge any existing relations (optional)
bool $overwriteWithEmpty Overwrite existing left values with empty right values. Only applicable with $priority='right'. (optional)

Return Value

Boolean

in DataObject at line 1126
$this forceChange()

Forces the record to think that all its data has changed.

Doesn't write to the database. Force-change preseved until next write. Existing CHANGE_VALUE or CHANGE_STRICT values are preserved.

Return Value

$this

at line 1046
ValidationResult validate()

Return Value

ValidationResult

in DataObject at line 1170
ValidationResult doValidate()

Public accessor for {see DataObject::validate()}

Return Value

ValidationResult

in DataObject at line 1218
ArrayList findCascadeDeletes(bool $recursive = true, ArrayList $list = null)

Find all objects that will be cascade deleted if this object is deleted

Notes: - If this object is versioned, objects will only be searched in the same stage as the given record. - This will only be useful prior to deletion, as post-deletion this record will no longer exist.

Parameters

bool $recursive True if recursive
ArrayList $list Optional list to add items to

Return Value

ArrayList list of objects

in DataObject at line 1258
DataObject populateDefaults()

Load the default values in from the self::$defaults array.

Will traverse the defaults of the current class and all its parent classes. Called by the constructor when creating new records.

Return Value

DataObject $this

in DataObject at line 1517
write(boolean $showDebug = false, boolean $forceInsert = false, boolean $forceWrite = false, boolean|array $writeComponents = false)

Writes all changes to this object to the database.

  • It will insert a record whenever ID isn't set, otherwise update.
    • All relevant tables will be updated.
    • $this->onBeforeWrite() gets called beforehand.
    • Extensions such as Versioned will ammend the database-write to ensure that a version is saved.

Parameters

boolean $showDebug Show debugging information
boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists
boolean $forceWrite Write to database even if there are no changes
boolean|array $writeComponents Call write() on all associated component instances which were previously retrieved through {@link getComponent()}, {@link getComponents()} or {@link getManyManyComponents()}. Default to false. The parameter can also be provided in the form of an array: ['recursive' => true, skip => ['Page'=>[1,2,3]]. This avoid infinite loops when one DataObject are components of each other.

Exceptions

ValidationException Exception that can be caught and handled by the calling function

in DataObject at line 1584
writeRelations()

Writes cached relation lists to the database, if possible

in DataObject at line 1607
DataObject writeComponents(bool $recursive = false, array $skip = [])

Write the cached components to the database. Cached components could refer to two different instances of the same record.

Parameters

bool $recursive Recursively write components
array $skip List of DataObject references to skip

Return Value

DataObject $this

in DataObject at line 1674
delete()

Delete this data object.

$this->onBeforeDelete() gets called. Note that in Versioned objects, both Stage and Live will be deleted.

in DataObject at line 1718
static delete_by_id(string $className, int $id)

Delete the record with the given ID.

Parameters

string $className The class name of the record to be deleted
int $id ID of record to be deleted

in DataObject at line 1736
array getClassAncestry()

Get the class ancestry, including the current class name.

The ancestry will be returned as an array of class names, where the 0th element will be the class that inherits directly from DataObject, and the last element will be the current class.

Return Value

array Class ancestry

in DataObject at line 1750
DataObject getComponent(string $componentName)

Return a unary component object from a one to one relationship, as a DataObject.

If no component is available, an 'empty component' will be returned for non-polymorphic relations, or for polymorphic relations with a class set.

Parameters

string $componentName Name of the component

Return Value

DataObject The component object. It's exact type will be that of the component.

Exceptions

Exception

in DataObject at line 1830
$this setComponent(string $componentName, DataObject|null $item)

Assign an item to the given component

Parameters

string $componentName
DataObject|null $item

Return Value

$this

in DataObject at line 1876
HasManyList|UnsavedRelationList getComponents(string $componentName, int|array $id = null)

Returns a one-to-many relation as a HasManyList

Parameters

string $componentName Name of the component
int|array $id Optional ID(s) for parent of this relation, if not the current record

Return Value

HasManyList|UnsavedRelationList The components of the one-to-many relationship.

in DataObject at line 1922
string getRelationClass(string $relationName)

Find the foreign class of a relation on this DataObject, regardless of the relation type.

Parameters

string $relationName Relation name.

Return Value

string Class name, or null if not found.

in DataObject at line 1959
string getRelationType(string $component)

Given a relation name, determine the relation type

Parameters

string $component Name of component

Return Value

string has_one, has_many, many_many, belongs_many_many or belongs_to

in DataObject at line 1989
DataList|DataObject inferReciprocalComponent(string $remoteClass, string $remoteRelation)

Given a relation declared on a remote class, generate a substitute component for the opposite side of the relation.

Notes on behaviour: - This can still be used on components that are defined on both sides, but do not need to be. - All has_ones on remote class will be treated as local has_many, even if they are belongs_to - Polymorphic relationships do not have two natural endpoints (only on one side) and thus attempting to infer them will return nothing. - Cannot be used on unsaved objects.

Parameters

string $remoteClass
string $remoteRelation

Return Value

DataList|DataObject The component, either as a list or single object

Exceptions

BadMethodCallException
InvalidArgumentException

in DataObject at line 2089
ManyManyList|UnsavedRelationList getManyManyComponents(string $componentName, int|array $id = null)

Returns a many-to-many component, as a ManyManyList.

Parameters

string $componentName Name of the many-many component
int|array $id Optional ID for parent of this relation, if not the current record

Return Value

ManyManyList|UnsavedRelationList The set of components

in DataObject at line 2158
string|array hasOne()

Return the class of a one-to-one component. If $component is null, return all of the one-to-one components and their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.

Return Value

string|array The class of the one-to-one component, or an array of all one-to-one components and their classes.

in DataObject at line 2171
string|array belongsTo(bool $classOnly = true)

Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and their class name will be returned.

Parameters

bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have the field data stripped off. It defaults to TRUE.

Return Value

string|array

in DataObject at line 2189
string|array|false hasMany(bool $classOnly = true)

Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many relationships and their classes will be returned.

Parameters

bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have the field data stripped off. It defaults to TRUE.

Return Value

string|array|false

in DataObject at line 2207
array|null manyManyExtraFields()

Return the many-to-many extra fields specification.

If you don't specify a component name, it returns all extra fields for all components available.

Return Value

array|null

in DataObject at line 2220
array|null manyMany()

Return information about a many-to-many component.

The return value is an array of (parentclass, childclass). If $component is null, then all many-many components are returned.

Return Value

array|null An array of (parentclass, childclass), or an array of all many-many components

See also

DataObjectSchema::manyManyComponent()

in DataObject at line 2237
array|false database_extensions(string $class)

This returns an array (if it exists) describing the database extensions that are required, or false if none

This is experimental, and is currently only a Postgres-specific enhancement.

Parameters

string $class

Return Value

array|false

in DataObject at line 2253
SearchContext getDefaultSearchContext()

Generates a SearchContext to be used for building and processing a generic search form for properties on this object.

Return Value

SearchContext

in DataObject at line 2277
FieldList scaffoldSearchFields(array $_params = null)

Determine which properties on the DataObject are searchable, and map them to their default {@link FormField} representations. Used for scaffolding a searchform for {@link ModelAdmin}.

Some additional logic is included for switching field labels, based on how generic or specific the field type is.

Used by {@link SearchContext}.

Parameters

array $_params 'fieldClasses': Associative array of field names as keys and FormField classes as values 'restrictFields': Numeric array of a field name whitelist

Return Value

FieldList

in DataObject at line 2352
FieldList scaffoldFormFields(array $_params = null)

Scaffold a simple edit form for all properties on this dataobject, based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.

Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.

Parameters

array $_params Associative array passing through properties to {@link FormScaffolder}.

Return Value

FieldList

at line 476
FieldList getCMSFields()

List of basic content editable file fields.

Note: These fields no longer affect the edit form in asset-admin. To add fields to the file edit form in asset-admin, you will need to add an extension to FileFormFactory and use the updateFormFields() hook.

Return Value

FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms.

in DataObject at line 2431
FieldList getCMSActions()

need to be overload by solid dataobject, so that the customised actions of that dataobject, including that dataobject's extensions customised actions could be added to the EditForm.

Return Value

FieldList an Empty FieldList(); need to be overload by solid subclass

in DataObject at line 2450
FieldList getFrontEndFields(array $params = null)

Used for simple frontend forms without relation editing or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()} by default. To customize, either overload this method in your subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.

Parameters

array $params See {@link scaffoldFormFields()}

Return Value

FieldList Always returns a simple field collection without TabSet.

in DataObject at line 2601
array getChangedFields(boolean|array $databaseFieldsOnly = false, int $changeLevel = self::CHANGE_STRICT)

Return the fields that have changed since the last write.

The change level affects what the functions defines as "changed": - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones. - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes, for example a change from 0 to null would not be included.

Example return: array( 'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE) )

Parameters

boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true to return all database fields, or an array for an explicit filter. false returns all fields.
int $changeLevel The strictness of what is defined as change. Defaults to strict

Return Value

array

in DataObject at line 2669
boolean isChanged(string $fieldName = null, int $changeLevel = self::CHANGE_STRICT)

Uses {@link getChangedFields()} to determine if fields have been changed since loading them from the database.

Parameters

string $fieldName Name of the database field to check, will check for any if not given
int $changeLevel See {@link getChangedFields()}

Return Value

boolean

in DataObject at line 2780
$this setCastedField(string $fieldName, mixed $value)

Set the value of the field, using a casting object.

This is useful when you aren't sure that a date is in SQL format, for example. setCastedField() can also be used, by forms, to set related data. For example, uploaded images can be saved into the Image table.

Parameters

string $fieldName
mixed $value New field value

Return Value

$this

in DataObject at line 2846
boolean hasDatabaseField(string $field)

Returns true if the given field exists as a database column

Parameters

string $field Name of the field

Return Value

boolean

in DataObject at line 2863
boolean can(string $perm, Member $member = null, array $context = array())

Returns true if the member is allowed to do the given action.

See {@link extendedCan()} for a more versatile tri-state permission control.

Parameters

string $perm The permission to be checked, such as 'View'.
Member $member The member whose permissions need checking. Defaults to the currently logged in user.
array $context Additional $context to pass to extendedCan()

Return Value

boolean True if the the member is allowed to do the given action

in DataObject at line 2907
boolean|null extendedCan(string $methodName, Member|int $member, array $context = array())

Process tri-state responses from permission-alterting extensions. The extensions are expected to return one of three values:

  • false: Disallow this permission, regardless of what other extensions say
    • true: Allow this permission, as long as no other extensions return false
    • NULL: Don't affect the outcome

This method itself returns a tri-state value, and is designed to be used like this:

$extended = $this->extendedCan('canDoSomething', $member); if($extended !== null) return $extended; else return $normalValue;

Parameters

string $methodName Method on the same object, e.g. {@link canEdit()}
Member|int $member
array $context Optional context

Return Value

boolean|null

at line 358
boolean canView(Member $member = null)

Parameters

Member $member

Return Value

boolean

at line 384
boolean canEdit(Member $member = null)

Check if this file can be modified

Parameters

Member $member

Return Value

boolean

at line 442
boolean canDelete(Member $member = null)

Check if this file can be deleted

Parameters

Member $member

Return Value

boolean

at line 411
boolean canCreate(Member $member = null, array $context = array())

Check if a file can be created

Parameters

Member $member
array $context Additional context-specific data which might affect whether (or where) this object could be created.

Return Value

boolean

in DataObject at line 2983
string debug()

Debugging used by Debug::show()

Return Value

string HTML data representing this object

in DataObject at line 3006
DBField dbObject(string $fieldName)

Return the DBField object that represents the given field.

This works similarly to obj() with 2 key differences: - it still returns an object even when the field has no value. - it only matches fields and not methods - it matches foreign keys generated by has_one relationships, eg, "ParentID"

Parameters

string $fieldName Name of the field

Return Value

DBField The field as a DBField object

in DataObject at line 3054
mixed relObject(string $fieldPath)

Traverses to a DBField referenced by relationships between data objects.

The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName).

If a relation is blank, this will return null instead. If a relation name is invalid (e.g. non-relation on a parent) this can throw a LogicException.

Parameters

string $fieldPath List of paths on this object. All items in this path must be ViewableData implementors

Return Value

mixed DBField of the field on the object or a DataList instance.

Exceptions

LogicException If accessing invalid relations

in DataObject at line 3092
mixed relField(string $fieldName)

Traverses to a field referenced by relationships between data objects, returning the value The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)

Parameters

string $fieldName string

Return Value

mixed Will return null on a missing value

in DataObject at line 3119
string getReverseAssociation(string $className)

Temporary hack to return an association name, based on class, to get around the mangle of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.

Parameters

string $className

Return Value

string

in DataObject at line 3160
static DataList get(string $callerClass = null, string|array $filter = "", string|array $sort = "", string $join = "", string|array $limit = null, string $containerClass = DataList::class)

Return all objects matching the filter sub-classes are automatically selected and included

Parameters

string $callerClass The class of objects to be returned
string|array $filter A filter to be inserted into the WHERE clause. Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
string|array $sort A sort expression to be inserted into the ORDER BY clause. If omitted, self::$default_sort will be used.
string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.
string|array $limit A limit expression to be inserted into the LIMIT clause.
string $containerClass The container class to return the results in.

Return Value

DataList The objects matching the filter, in the class specified by $containerClass

in DataObject at line 3225
static DataObject|null get_one(string|null $callerClass = null, string|array $filter = "", boolean $cache = true, string $orderBy = "")

Return the first item matching the given query.

All calls to get_one() are cached.

The filter argument supports parameterised queries (see SQLSelect::addWhere() for syntax examples). Because of that (and differently from e.g. DataList::filter()) you need to manually escape the field names: $member = DataObject::get_one('Member', [ '"FirstName"' => 'John' ]);

Parameters

string|null $callerClass The class of objects to be returned. Defaults to the class that calls the method e.g. MyObject::get_one() will return a MyObject
string|array $filter A filter to be inserted into the WHERE clause. Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
boolean $cache Use caching
string $orderBy A sort expression to be inserted into the ORDER BY clause.

Return Value

DataObject|null The first item matching the query

at line 1394
DataObject flushCache(boolean $persistent = true)

Flush the cached results for all relations (has_one, has_many, many_many) Also clears any cached aggregate data.

Parameters

boolean $persistent When true will also clear persistent data stored in the Cache system. When false will just clear session-local cached data

Return Value

DataObject $this

in DataObject at line 3291
static flush_and_destroy_cache()

Flush the get_one global cache and destroy associated objects.

at line 1402
static reset()

Reset all global caches associated with DataObject.

in DataObject at line 3332
static DataObject get_by_id(string|int $classOrID, int|bool $idOrCache = null, boolean $cache = true)

Return the given element, searching by ID.

This can be called either via DataObject::get_by_id(MyClass::class, $id) or MyClass::get_by_id($id)

Parameters

string|int $classOrID The class of the object to be returned, or id if called on target class
int|bool $idOrCache The id of the element, or cache if called on target class
boolean $cache See {@link get_one()}

Return Value

DataObject The element

in DataObject at line 3354
string baseTable()

Get the name of the base table for this object

Return Value

string

in DataObject at line 3364
string baseClass()

Get the base class for this object

Return Value

string

in DataObject at line 3380
array getSourceQueryParams()

Return Value

array

See also

$sourceQueryParams

in DataObject at line 3390
array getInheritableQueryParams()

Get list of parameters that should be inherited to relations on this object

Return Value

array

in DataObject at line 3401
setSourceQueryParams(array $array)

Parameters

array $array

See also

$sourceQueryParams

in DataObject at line 3411
setSourceQueryParam(string $key, string $value)

Parameters

string $key
string $value

See also

$sourceQueryParams

in DataObject at line 3421
string getSourceQueryParam(string $key)

Parameters

string $key

Return Value

string

See also

$sourceQueryParams

in DataObject at line 3436
requireTable()

Check the database schema and update it as necessary.

in DataObject at line 3539
requireDefaultRecords()

Add default records to database. This function is called whenever the database is built, after the database tables have all been created. Overload this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().

in DataObject at line 3566
array searchableFields()

Get the default searchable fields for this object, as defined in the $searchable_fields list. If searchable fields are not defined on the data object, uses a default selection of summary fields.

Return Value

array

in DataObject at line 3666
array fieldLabels(boolean $includerelations = true)

Get any user defined searchable fields labels that exist. Allows overriding of default field names in the form interface actually presented to the user.

The reason for keeping this separate from searchable_fields, which would be a logical place for this functionality, is to avoid bloating and complicating the configuration array. Currently much of this system is based on sensible defaults, and this property would generally only be set in the case of more complex relationships between data object being required in the search interface.

Generates labels based on name of the field itself, if no static property {@link self::field_labels} exists.

Parameters

boolean $includerelations a boolean value to indicate if the labels returned include relation fields

Return Value

array Array of all element labels

in DataObject at line 3732
string fieldLabel(string $name)

Get a human-readable label for a single field, see {@link fieldLabels()} for more details.

Parameters

string $name Name of the field

Return Value

string Label of the field

in DataObject at line 3745
array summaryFields()

Get the default summary fields for this object.

Return Value

array

in DataObject at line 3804
array defaultSearchFilters()

Defines a default list of filters for the search context.

If a filter class mapping is defined on the data object, it is constructed here. Otherwise, the default filter specified in {@link DBField} is used.

Return Value

array

in DataObject at line 3825
boolean isInDB()

Return Value

boolean True if the object is in the database

in DataObject at line 3838
static disable_subclass_access()

Temporarily disable subclass access in data object qeur

in DataObject at line 3843
static enable_subclass_access()

in DataObject at line 4065
array provideI18nEntities()

Returns the list of provided translations for this object.

Note: Pluralised forms are always returned in array format.

Example usage: class MyTestClass implements i18nEntityProvider { public function provideI18nEntities() { $entities = []; foreach($this->config()->get('my_static_array') as $key => $value) { $entities["MyTestClass.my_static_array_{$key}"] = $value; } $entities["MyTestClass.PLURALS"] = [ 'one' => 'A test class', 'other' => '{count} test classes', ] return $entities; } }

Example usage in {@link DataObject->provideI18nEntities()}.

You can ask textcollector to add the provided entity to a different module. Simply wrap the returned value for any item in an array with the format: [ 'default' => $defaultValue, 'module' => $module ]

class MyTestClass implements i18nEntityProvider { public function provideI18nEntities() { $entities = [ 'MyOtherModuleClass.MYENTITY' => [ 'default' => $value, 'module' => 'myothermodule', ] ]; } return $entities; }

Return Value

array Map of keys to default values, which are strings in the default case, and array-form for pluralisations.

in DataObject at line 4107
DataObject getJoin()

If selected through a many_many through relation, this is the instance of the joined record

Return Value

DataObject

in DataObject at line 4119
$this setJoin(DataObject $object, string $alias = null)

Set joining object

Parameters

DataObject $object
string $alias Alias

Return Value

$this

in DataObject at line 4142
ArrayList findRelatedObjects(string $source, bool $recursive = true, ArrayList $list = null)

Find objects in the given relationships, merging them into the given list

Parameters

string $source Config property to extract relationships from
bool $recursive True if recursive
ArrayList $list If specified, items will be added to this list. If not, a new instance of ArrayList will be constructed and returned

Return Value

ArrayList The list of related objects

in DataObject at line 4191
ArrayList mergeRelatedObjects(ArrayList $list, mixed $items)

Helper method to merge owned/owning items into a list.

Items already present in the list will be skipped.

Parameters

ArrayList $list Items to merge into
mixed $items List of new items to merge

Return Value

ArrayList List of all newly added items that did not already exist in $list

in ImageManipulation at line 67
$this setAllowGeneration(bool $allow)

Set whether image resizes are allowed

Parameters

bool $allow

Return Value

$this

in ImageManipulation at line 78
bool getAllowGeneration()

Check if resizes are allowed

Return Value

bool

in ImageManipulation at line 88
DBFile existingOnly()

Return clone of self which promises to only return existing thumbnails

Return Value

DBFile

at line 1120
string getString()

Return Value

string Data from the file in this container

at line 1112
resource getStream()

Return Value

resource Data stream to the asset in this container

at line 799
string getURL(bool $grant = true)

Gets the URL of this file

Parameters

bool $grant Ensures that the url for any protected assets is granted for the current user. If set to true, and the file is currently in protected mode, the asset store will ensure the returned URL is accessible for the duration of the current session / user. This will have no effect if the file is in published mode. This will not grant access to users other than the owner of the current session.

Return Value

string public url to the asset in this container

at line 783
string getAbsoluteURL()

Gets the URL of this file

Return Value

string The absolute URL to the asset in this container

at line 1096
array|null getMetaData()

Get metadata for this file

Return Value

array|null File information

at line 1104
string getMimeType()

Get mime type

Return Value

string Mime type for this file

at line 1038
int getAbsoluteSize()

Return file size in bytes.

Return Value

int

at line 1166
string getFilename()

Get value of filename

Return Value

string

at line 1171
string getHash()

Get value of hash

Return Value

string

at line 1176
string getVariant()

Get value of variant

Return Value

string

at line 1161
bool getIsImage()

Determine if a valid non-empty image exists behind this asset

Return Value

bool

in ImageManipulation at line 241
AssetContainer Pad(int $width, int $height, string $backgroundColor = 'FFFFFF', int $transparencyPercent)

Fit image to specified dimensions and fill leftover space with a solid colour (default white). Use in templates with $Pad.

Parameters

int $width The width to size to
int $height The height to size to
string $backgroundColor
int $transparencyPercent Level of transparency

Return Value

AssetContainer

in ImageManipulation at line 262
AssetContainer Resampled()

Forces the image to be resampled, if possible

Return Value

AssetContainer

in ImageManipulation at line 285
updateURL(string $url)

Update the url to point to a resampled version if forcing

Parameters

string $url

in ImageManipulation at line 314
AssetContainer ResizedImage(int $width, int $height)

Generate a resized copy of this image with the given width & height.

This can be used in templates with $ResizedImage but should be avoided, as it's the only image manipulation function which can skew an image.

Parameters

int $width Width to resize to
int $height Height to resize to

Return Value

AssetContainer

in ImageManipulation at line 334
AssetContainer Fit(int $width, int $height)

Scale image proportionally to fit within the specified bounds

Parameters

int $width The width to size within
int $height The height to size within

Return Value

AssetContainer

in ImageManipulation at line 375
AssetContainer FitMax(int $width, int $height)

Proportionally scale down this image if it is wider or taller than the specified dimensions.

Similar to Fit but without up-sampling. Use in templates with $FitMax.

Parameters

int $width The maximum width of the output image
int $height The maximum height of the output image

Return Value

AssetContainer

in ImageManipulation at line 419
AssetContainer ScaleWidth(int $width)

Scale image proportionally by width. Use in templates with $ScaleWidth.

Parameters

int $width The width to set

Return Value

AssetContainer

in ImageManipulation at line 439
AssetContainer ScaleMaxWidth(int $width)

Proportionally scale down this image if it is wider than the specified width.

Similar to ScaleWidth but without up-sampling. Use in templates with $ScaleMaxWidth.

Parameters

int $width The maximum width of the output image

Return Value

AssetContainer

in ImageManipulation at line 457
AssetContainer ScaleHeight(int $height)

Scale image proportionally by height. Use in templates with $ScaleHeight.

Parameters

int $height The height to set

Return Value

AssetContainer

in ImageManipulation at line 477
AssetContainer ScaleMaxHeight(int $height)

Proportionally scale down this image if it is taller than the specified height.

Similar to ScaleHeight but without up-sampling. Use in templates with $ScaleMaxHeight.

Parameters

int $height The maximum height of the output image

Return Value

AssetContainer

in ImageManipulation at line 498
AssetContainer CropWidth(int $width)

Crop image on X axis if it exceeds specified width. Retain height.

Use in templates with $CropWidth. Example: $Image.ScaleHeight(100).$CropWidth(100)

Parameters

int $width The maximum width of the output image

Return Value

AssetContainer

in ImageManipulation at line 520
AssetContainer CropHeight(int $height)

Crop image on Y axis if it exceeds specified height. Retain width.

Use in templates with $CropHeight. Example: $Image.ScaleWidth(100).CropHeight(100)

Parameters

int $height The maximum height of the output image

Return Value

AssetContainer

in ImageManipulation at line 544
AssetContainer FillMax(int $width, int $height)

Crop this image to the aspect ratio defined by the specified width and height, then scale down the image to those dimensions if it exceeds them.

Similar to Fill but without up-sampling. Use in templates with $FillMax.

Parameters

int $width The relative (used to determine aspect ratio) and maximum width of the output image
int $height The relative (used to determine aspect ratio) and maximum height of the output image

Return Value

AssetContainer

in ImageManipulation at line 584
AssetContainer Fill(int $width, int $height)

Resize and crop image to fill specified dimensions.

Use in templates with $Fill

Parameters

int $width Width to crop to
int $height Height to crop to

Return Value

AssetContainer

in ImageManipulation at line 604
AssetContainer Quality(int $quality)

Set the quality of the resampled image

Parameters

int $quality Quality level from 0 - 100

Return Value

AssetContainer

Exceptions

InvalidArgumentException

in ImageManipulation at line 618
DBFile|DBHTMLText CMSThumbnail()

Default CMS thumbnail

Return Value

DBFile|DBHTMLText Either a resized thumbnail, or html for a thumbnail icon

in ImageManipulation at line 630
AssetContainer|DBHTMLText StripThumbnail()

Generates a thumbnail for use in the gridfield view

Return Value

AssetContainer|DBHTMLText Either a resized thumbnail, or html for a thumbnail icon

in ImageManipulation at line 642
AssetContainer|DBHTMLText PreviewThumbnail()

Get preview for this file

Return Value

AssetContainer|DBHTMLText Either a resized thumbnail, or html for a thumbnail icon

in ImageManipulation at line 655
AssetContainer Thumbnail(int $width, int $height)

Default thumbnail generation for Images

Parameters

int $width
int $height

Return Value

AssetContainer

in ImageManipulation at line 669
AssetContainer|DBHTMLText ThumbnailIcon(int $width, int $height)

Thumbnail generation for all file types.

Resizes images, but returns an icon <img /> tag if this is not a resizable image

Parameters

int $width
int $height

Return Value

AssetContainer|DBHTMLText

in ImageManipulation at line 679
DBHTMLText IconTag()

Get HTML for img containing the icon for this file

Return Value

DBHTMLText

in ImageManipulation at line 698
string ThumbnailURL(int $width, int $height)

Get URL to thumbnail of the given size.

May fallback to default icon

Parameters

int $width
int $height

Return Value

string

in ImageManipulation at line 714
string getIcon()

Return the relative URL of an icon for the file type, based on the {@link appCategory()} value.

Images are searched for in "framework/images/app_icons/".

Return Value

string URL to icon

in ImageManipulation at line 726
Image_Backend getImageBackend()

Get Image_Backend instance for this image

Return Value

Image_Backend

in ImageManipulation at line 751
$this setImageBackend(Image_Backend $backend)

Parameters

Image_Backend $backend

Return Value

$this

in ImageManipulation at line 762
int getWidth()

Get the width of this image.

Return Value

int

in ImageManipulation at line 776
int getHeight()

Get the height of this image.

Return Value

int

in ImageManipulation at line 790
int getOrientation()

Get the orientation of this image.

Return Value

int ORIENTATION_SQUARE | ORIENTATION_PORTRAIT | ORIENTATION_LANDSCAPE

in ImageManipulation at line 810
boolean isSize(int $width, int $height)

Determine if this image is of the specified size

Parameters

int $width Width to check
int $height Height to check

Return Value

boolean

in ImageManipulation at line 821
boolean isWidth(int $width)

Determine if this image is of the specified width

Parameters

int $width Width to check

Return Value

boolean

in ImageManipulation at line 833
boolean isHeight(int $height)

Determine if this image is of the specified width

Parameters

int $height Height to check

Return Value

boolean

in ImageManipulation at line 847
DBFile manipulateImage(string $variant, callable $callback)

Wrapper for manipulate that passes in and stores Image_Backend objects instead of tuples

Parameters

string $variant
callable $callback Callback which takes an Image_Backend object, and returns an Image_Backend result. If this callback returns true then the current image will be duplicated without modification.

Return Value

DBFile The manipulated file

in ImageManipulation at line 917
DBFile manipulate(string $variant, callable $callback)

Generate a new DBFile instance using the given callback if it hasn't been created yet, or return the existing one if it has.

Parameters

string $variant name of the variant to create
callable $callback Callback which should return a new tuple as an array. This callback will be passed the backend, filename, hash, and variant This will not be called if the file does not need to be created.

Return Value

DBFile The manipulated file

in ImageManipulation at line 994
string variantName($format, $arg = null)

Name a variant based on a format with arbitrary parameters

Parameters

$format
$arg

Return Value

string

in ImageManipulation at line 1013
array|null variantParts($variantName)

Reverses {@link variantName()}.

The "format" part of a variant name is a method name on the owner of this trait. For legacy reasons, there's no delimiter between this part, and the encoded arguments. This means we have to use a whitelist of "known formats", based on methods available on the {@link Image} class as the "main" user of this trait. This class is commonly decorated with additional manipulation methods through {@link DataExtension}.

Parameters

$variantName

Return Value

array|null An array of arguments passed to {@link variantName}. The first item is the "format".

Exceptions

InvalidArgumentException

at line 272
static get_shortcodes()

at line 296
static File find(string $filename)

Find a File object by the given filename.

Parameters

string $filename Filename to search for, including any custom parent directories.

Return Value

File

Just an alias function to keep a consistent API with SiteTree

Return Value

string The link to the file

deprecated 4.0

Just an alias function to keep a consistent API with SiteTree

Return Value

string The absolute link to the file

at line 349
string getTreeTitle()

Return Value

string

at line 500
string getStatusTitle()

Get title for current file status

Return Value

string

at line 520
static string get_app_category(string $ext)

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

Parameters

string $ext Extension to check

Return Value

string

at line 537
static array get_category_extensions(array|string $categories)

For a category or list of categories, get the list of file extensions

Parameters

array|string $categories List of categories, or single category

Return Value

array

at line 572
string appCategory()

Returns a category based on the file extension.

Return Value

string

at line 580
onAfterUpload()

Should be called after the file was uploaded

at line 660
onAfterRevertToLive()

at line 705
bool updateFilesystem()

This will check if the parent record and/or name do not match the name on the underlying DBFile record, and if so, copy this file to the new location, and update the record to point to this new file.

This method will update the File {see DBFile} field value on success, so it must be called before writing to the database

Return Value

bool True if changed

at line 752
true|null collateDescendants(string $condition, array $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.

Parameters

string $condition The PHP condition to be evaluated. The page will be called $item
array $collator An array, passed by reference, to collect all of the matching descendants.

Return Value

true|null

at line 813
string getSourceURL(bool $grant = true)

Get URL, but without resampling.

Parameters

bool $grant Ensures that the url for any protected assets is granted for the current user.

Return Value

string

at line 827
string generateFilename()

Get expected value of Filename tuple value. Will be used to trigger a file move on draft stage.

Return Value

string

at line 845
string renameFile(string $newName)

Rename this file.

Note: This method will immediately save to the database to maintain filesystem consistency with the database.

Parameters

string $newName

Return Value

string Updated Filename

at line 852
string copyFile(string $newName)

Copy to new filename.

This will not automatically point to the new file (as renameFile() does)

Parameters

string $newName

Return Value

string Updated filename

at line 868
$this setFilename(string $filename)

Update the ParentID and Name for the given filename.

On save, the underlying DBFile record will move the underlying file to this location. Thus it will not update the underlying Filename value until this is done.

Parameters

string $filename

Return Value

$this

at line 900
string getExtension()

Returns the file extension

Return Value

string

at line 919
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").

Examples: - "myfile" returns "" - "myfile.txt" returns "txt" - "myfile.tar.gz" returns "gz"

Parameters

string $filename

Return Value

string

at line 930
static string get_icon_for_extension(string $extension)

Given an extension, determine the icon that should be used

Parameters

string $extension

Return Value

string Icon filename relative to base url

at line 955
string getFileType()

Return the type of file for the given extension on the current file name.

Return Value

string

at line 966
static string get_file_type(string $filename)

Get descriptive type of file based on filename

Parameters

string $filename

Return Value

string Description of file

at line 988
string|false getSize()

Returns the size of the file type in an appropriate format.

Return Value

string|false String value, or false if doesn't exist

at line 1003
static string format_size(int $size)

Formats a file size (eg: (int)42 becomes string '42 bytes')

Parameters

int $size

Return Value

string

at line 1027
static int ini2bytes(string $iniValue) deprecated

deprecated 5.0 Use Convert::memstring2bytes() instead

Convert a php.ini value (eg: 512M) to bytes

Parameters

string $iniValue

Return Value

int

at line 1069
static String get_class_for_file_extension(String $ext)

Maps a {@link File} subclass to a specific extension.

By default, files with common image extensions will be created as {@link Image} instead of {@link File} when using {@link Folder::constructChild}, {@link Folder::addUploadToFolder}), and the {@link Upload} class (either directly or through {@link FileField}). For manually instanciated files please use this mapping getter.

Caution: Changes to mapping doesn't apply to existing file records in the database. Also doesn't hook into {@link Object::getCustomClass()}.

Parameters

String $ext File extension, without dot prefix. Use an asterisk ('*') to specify a generic fallback if no mapping is found for an extension.

Return Value

String Classname for a subclass of {@link File}

at line 1081
static set_class_for_file_extension(String|array $exts, String $class)

See {@link get_class_for_file_extension()}.

Parameters

String|array $exts
String $class

at line 1128
array setFromLocalFile(string $path, string $filename = null, string $hash = null, string $variant = null, array $config = array())

Assign a local file to the backend.

Parameters

string $path Absolute filesystem path to file
string $filename Optional path to ask the backend to name as. Will default to the filename of the $path, excluding directories.
string $hash Hash of original file, if storing a variant.
string $variant Name of variant, if storing a variant.
array $config Write options. {see AssetStore}

Return Value

array Tuple associative array (Filename, Hash, Variant) Unless storing a variant, the hash will be calculated from the local file content.

at line 1139
array setFromStream(resource $stream, string $filename, string $hash = null, string $variant = null, array $config = array())

Assign a stream to the backend

Parameters

resource $stream Streamable resource
string $filename Name for the resulting file
string $hash Hash of original file, if storing a variant.
string $variant Name of variant, if storing a variant.
array $config Write options. {see AssetStore}

Return Value

array Tuple associative array (Filename, Hash, Variant) Unless storing a variant, the hash will be calculated from the raw stream.

at line 1150
array setFromString(string $data, string $filename, string $hash = null, string $variant = null, array $config = array())

Assign a set of data to the backend

Parameters

string $data Raw binary/text content
string $filename Name for the resulting file
string $hash Hash of original file, if storing a variant.
string $variant Name of variant, if storing a variant.
array $config Write options. {see AssetStore}

Return Value

array Tuple associative array (Filename, Hash, Variant) Unless storing a variant, the hash will be calculated from the given data.

at line 1186
string forTemplate()

Return a html5 tag of the appropriate for this file (normally img or a)

Return Value

string

at line 1196
string getTag()

Return a html5 tag of the appropriate for this file (normally img or a)

Return Value

string

at line 1210
BackLinkTracking()

Get the back-link tracking objects that link to this file via HTML fields

at line 1230
int BackLinkTrackingCount()

Count of backlinks Note: Doesn't filter broken records

Return Value

int

at line 1244
static string join_paths($part = null)

Joins one or more segments together to build a Filename identifier.

Note that the result will not have a leading slash, and should not be used with local file paths.

Parameters

$part

Return Value

string

at line 1262
bool deleteFile()

Delete a file (and all variants).

{see AssetStore::delete()}

Return Value

bool Flag if a file was deleted

at line 1267
string getVisibility()

Determine visibility of the given file

Return Value

string one of values defined by the constants VISIBILITY_PROTECTED or VISIBILITY_PUBLIC, or null if the file does not exist

at line 1272
publishFile()

Publicly expose the file (and all variants) identified by the given filename and hash {see AssetStore::publish}

at line 1277
protectFile()

Protect a file (and all variants) from public access, identified by the given filename and hash.

{see AssetStore::protect()}

at line 1282
grantFile()

Ensures that access to the specified protected file is granted for the current user.

If this file is currently in protected mode, the asset store will ensure the returned asset for the duration of the current session / user. This will have no effect if the file is in published mode. This will not grant access to users other than the owner of the current session. Does not require a member to be logged in.

at line 1287
revokeFile()

Revoke access to the given file for the current user.

Note: This will have no effect if the given file is public

at line 1292
bool canViewFile()

Check if the current user can view the given file.

Return Value

bool True if the file is verified and grants access to the current session / user.

Return Value

string Link to the CMS-author view. Should point to a controller subclassing {@link LeftAndMain}. Example: http://mysite.com/admin/edit/6

Determine the preview link, if available, for this object.

If no preview is available for this record, it may return null.

Parameters

string $action

Return Value

string Link to the end-user view for this record. Example: http://mysite.com/my-record

at line 1319
PermissionChecker getPermissionChecker()

Return Value

PermissionChecker

at line 1330
providePermissions()

Return a map of permission codes to add to the dropdown shown in the Security section of the CMS.

array( 'VIEW_SITE' => 'View the site', );

at line 1356
static array getAllowedExtensions()

Get the list of globally allowed file extensions for file uploads.

Specific extensions can be disabled with configuration, for example:

SilverStripe\Assets\File:
  allowed_extensions:
    dmg: false
    docx: false

Return Value

array

at line 102
File Parent()

Returns parent File

Return Value

File

at line 102
Member Owner()

Returns Member object of file owner.

Return Value

Member