MediaWiki  master
LocalFile Class Reference

Local file in the wiki's own database. More...

Inheritance diagram for LocalFile:
Collaboration diagram for LocalFile:

Public Member Functions

 __construct ( $title, $repo)
 Do not call this except from inside a repo class. More...
 
 __destruct ()
 Clean up any dangling locks. More...
 
 acquireFileLock ( $timeout=0)
 Acquire an exclusive lock on the file, indicating an intention to write to the file backend. More...
 
 deleteFile ( $reason, UserIdentity $user, $suppress=false)
 Delete all versions of the file. More...
 
 deleteOldFile ( $archiveName, $reason, UserIdentity $user, $suppress=false)
 Delete an old version of the file. More...
 
 exists ()
 canRender inherited More...
 
 getBitDepth ()
 @stable to override More...
 
 getDescription ( $audience=self::FOR_PUBLIC, Authority $performer=null)
 
 getDescriptionShortUrl ()
 Get short description URL for a file based on the page ID. More...
 
 getDescriptionText (Language $lang=null)
 Get the HTML text of the description page This is not used by ImagePage for local files, since (among other things) it skips the parser cache. More...
 
 getDescriptionTouched ()
 
 getDescriptionUrl ()
 isMultipage inherited More...
 
 getHeight ( $page=1)
 Return the height of the image @stable to override. More...
 
 getHistory ( $limit=null, $start=null, $end=null, $inc=true)
 purgeDescription inherited More...
 
 getMediaType ()
 Returns the type of the media in the file. More...
 
 getMetadata ()
 Get handler-specific metadata as a serialized string. More...
 
 getMetadataArray ()
 Get unserialized handler-specific metadata. More...
 
 getMetadataForDb (IDatabase $db)
 Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata. More...
 
 getMetadataItems (array $itemNames)
 Get multiple elements of the unserialized handler-specific metadata. More...
 
 getMimeType ()
 Returns the MIME type of the file. More...
 
 getMutableCacheKeys (WANObjectCache $cache)
 
 getRepo ()
 
 getSha1 ()
 
 getSize ()
 Returns the size of the image file, in bytes @stable to override. More...
 
 getTimestamp ()
 
 getUpgraded ()
 
 getUploader (int $audience=self::FOR_PUBLIC, Authority $performer=null)
 
 getWidth ( $page=1)
 Return the width of the image @stable to override. More...
 
 invalidateCache ()
 Purge the file object/metadata cache. More...
 
 isCacheable ()
 
 isMissing ()
 splitMime inherited More...
 
 load ( $flags=0)
 Load file metadata from cache or DB, unless already loaded. More...
 
 loadFromFile ( $path=null)
 Load metadata from the file itself. More...
 
 loadFromRow ( $row, $prefix='img_')
 Load file metadata from a DB result row. More...
 
 lock ()
 Start an atomic DB section and lock the image for update or increments a reference counter if the lock is already held. More...
 
 maybeUpgradeRow ()
 Upgrade a row if it needs it. More...
 
 move ( $target)
 getLinksTo inherited More...
 
 nextHistoryLine ()
 Returns the history of this file, line by line. More...
 
 prerenderThumbnails ()
 Prerenders a configurable set of thumbnails. More...
 
 publish ( $src, $flags=0, array $options=[])
 Move or copy a file to its public location. More...
 
 purgeCache ( $options=[])
 Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN. More...
 
 purgeOldThumbnails ( $archiveName)
 Delete cached transformed files for an archived version only. More...
 
 purgeThumbnails ( $options=[])
 Delete cached transformed files for the current version only. More...
 
 recordUpload3 (string $oldver, string $comment, string $pageText, Authority $performer, $props=false, $timestamp=false, $tags=[], bool $createNullRevision=true, bool $revert=false)
 Record a file upload in the upload log and the image table (version 3) More...
 
 releaseFileLock ()
 Release a lock acquired with acquireFileLock(). More...
 
 resetHistory ()
 Reset the history pointer to the first element of the history. More...
 
 restore ( $versions=[], $unsuppress=false)
 Restore all or specified deleted revisions to the given file. More...
 
 unlock ()
 Decrement the lock reference count and end the atomic section if it reaches zero. More...
 
 upgradeRow ()
 Fix assorted version-related problems with the image row by reloading it from the file. More...
 
 upload ( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, Authority $uploader=null, $tags=[], $createNullRevision=true, $revert=false)
 getHashPath inherited More...
 
- Public Member Functions inherited from File
 __get ( $name)
 
 allowInlineDisplay ()
 Alias for canRender() More...
 
 canAnimateThumbIfAppropriate ()
 Will the thumbnail be animated if one would expect it to be. More...
 
 canRender ()
 Checks if the output of transform() for this file is likely to be valid. More...
 
 convertMetadataVersion ( $metadata, $version)
 get versioned metadata More...
 
 createThumb ( $width, $height=-1)
 Create a thumbnail of the image having the specified width/height. More...
 
 formatMetadata ( $context=false)
 
 generateAndSaveThumb ( $tmpFile, $transformParams, $flags)
 Generates a thumbnail according to the given parameters and saves it to storage. More...
 
 generateThumbName ( $name, $params)
 Generate a thumbnail file name from a name and specified parameters. More...
 
 getArchivePath ( $suffix=false)
 Get the path of the archived file. More...
 
 getArchiveRel ( $suffix=false)
 Get the path of an archived file relative to the public zone root. More...
 
 getArchiveThumbPath ( $archiveName, $suffix=false)
 Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified. More...
 
 getArchiveThumbUrl ( $archiveName, $suffix=false)
 Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified. More...
 
 getArchiveUrl ( $suffix=false)
 Get the URL of the archive directory, or a particular file if $suffix is specified. More...
 
 getArchiveVirtualUrl ( $suffix=false)
 Get the public zone virtual URL for an archived version source file. More...
 
 getAvailableLanguages ()
 Gives a (possibly empty) list of IETF languages to render the file in. More...
 
 getCanonicalUrl ()
 
 getCommonMetaArray ()
 Like getMetadata but returns a handler independent array of common values. More...
 
 getContentHeaders ()
 
 getDefaultRenderLanguage ()
 In files that support multiple language, what is the default language to use if none specified. More...
 
 getDimensionsString ()
 
 getDisplayWidthHeight ( $maxWidth, $maxHeight, $page=1)
 Get the width and height to display image at. More...
 
 getExtension ()
 Get the file extension, e.g. More...
 
 getFilePageThumbUrl ( $url)
 Append a version parameter to the end of a file URL Only to be used on File pages. More...
 
 getFullUrl ()
 Return a fully-qualified URL to the file. More...
 
 getHandler ()
 Get a MediaHandler instance for this file. More...
 
 getHandlerState (string $key)
 Get a value, or null if it does not exist. More...
 
 getHashPath ()
 Get the filename hash component of the directory including trailing slash, e.g. More...
 
 getLastError ()
 Get last thumbnailing error. More...
 
 getLength ()
 Get the duration of a media file in seconds. More...
 
 getLocalRefPath ()
 Get an FS copy or original of this file and return the path. More...
 
 getLongDesc ()
 
 getMatchedLanguage ( $userPreferredLanguage)
 Get the IETF language code from the available languages for this file that matches the language requested by the user. More...
 
 getMetadataItem (string $itemName)
 Get a specific element of the unserialized handler-specific metadata. More...
 
 getName ()
 Return the name of this file. More...
 
 getOriginalTitle ()
 Return the title used to find this file. More...
 
 getPath ()
 Return the storage path to the file. More...
 
 getRedirected ()
 
 getRel ()
 Get the path of the file relative to the public zone root. More...
 
 getRepoName ()
 Returns the name of the repository. More...
 
 getShortDesc ()
 
 getStorageKey ()
 Get the deletion archive key, "<sha1>.<ext>". More...
 
 getThumbDisposition ( $thumbName, $dispositionType='inline')
 
 getThumbnailBucket ( $desiredWidth, $page=1)
 Return the smallest bucket from $wgThumbnailBuckets which is at least $wgThumbnailMinimumBucketDistance larger than $desiredWidth. More...
 
 getThumbnailSource ( $params)
 Returns the most appropriate source image for the thumbnail, given a target thumbnail size. More...
 
 getThumbPath ( $suffix=false)
 Get the path of the thumbnail directory, or a particular file if $suffix is specified. More...
 
 getThumbRel ( $suffix=false)
 Get the path, relative to the thumbnail zone root, of the thumbnail directory or a particular file if $suffix is specified. More...
 
 getThumbUrl ( $suffix=false)
 Get the URL of the thumbnail directory, or a particular file if $suffix is specified. More...
 
 getThumbVirtualUrl ( $suffix=false)
 Get the virtual URL for a thumbnail file or directory. More...
 
 getTitle ()
 Return the associated title object. More...
 
 getTranscodedPath ( $suffix=false)
 Get the path of the transcoded directory, or a particular file if $suffix is specified. More...
 
 getTranscodedUrl ( $suffix=false)
 Get the URL of the transcoded directory, or a particular file if $suffix is specified. More...
 
 getUnscaledThumb ( $handlerParams=[])
 Get a ThumbnailImage which is the same size as the source. More...
 
 getUrl ()
 Return the URL of the file. More...
 
 getUrlRel ()
 Get urlencoded path of the file relative to the public zone root. More...
 
 getViewURL ()
 
 getVirtualUrl ( $suffix=false)
 Get the public zone virtual URL for a current version source file. More...
 
 getVisibility ()
 Return the deletion bitfield STUB. More...
 
 iconThumb ()
 Get a ThumbnailImage representing a file type icon. More...
 
 isDeleted ( $field)
 Is this file a "deleted" file in a private archive? STUB. More...
 
 isExpensiveToThumbnail ()
 True if creating thumbnails from the file is large or otherwise resource-intensive. More...
 
 isLocal ()
 Returns true if the file comes from the local file repository. More...
 
 isMultipage ()
 Returns 'true' if this file is a type which supports multiple pages, e.g. More...
 
 isOld ()
 Returns true if the image is an old version STUB. More...
 
 isSafeFile ()
 Determines if this media file is in a format that is unlikely to contain viruses or malicious content. More...
 
 isTransformedLocally ()
 Whether the thumbnails created on the same server as this code is running. More...
 
 isVectorized ()
 Return true if the file is vectorized. More...
 
 isVisible ()
 Returns true if file exists in the repository and can be included in a page. More...
 
 mustRender ()
 Return true if the file is of a type that can't be directly rendered by typical browsers and needs to be re-rasterized. More...
 
 pageCount ()
 Returns the number of pages of a multipage document, or false for documents which aren't multipage documents. More...
 
 purgeDescription ()
 Purge the file description page, but don't go after pages using the file. More...
 
 purgeEverything ()
 Purge metadata and all affected pages when the file is created, deleted, or majorly updated. More...
 
 redirectedFrom ( $from)
 
 setHandlerState (string $key, $value)
 Set a value. More...
 
 thumbName ( $params, $flags=0)
 Return the file name of a thumbnail with the specified parameters. More...
 
 transform ( $params, $flags=0)
 Transform a media file. More...
 
 userCan ( $field, Authority $performer)
 Determine if the current user is allowed to view a particular field of this file, if it's marked as deleted. More...
 
 wasDeleted ()
 Was this file ever deleted from the wiki? More...
 

Static Public Member Functions

static getQueryInfo (array $options=[])
 Return the tables, fields, and join conditions to be selected to create a new localfile object. More...
 
static newFromKey ( $sha1, $repo, $timestamp=false)
 Create a LocalFile from a SHA-1 key Do not call this except from inside a repo class. More...
 
static newFromRow ( $row, $repo)
 Create a LocalFile from a title Do not call this except from inside a repo class. More...
 
static newFromTitle ( $title, $repo, $unused=null)
 Create a LocalFile from a title Do not call this except from inside a repo class. More...
 
- Static Public Member Functions inherited from File
static checkExtensionCompatibility (File $old, $new)
 Checks if file extensions are compatible. More...
 
static compare (File $a, File $b)
 Callback for usort() to do file sorts by name. More...
 
static normalizeExtension ( $extension)
 Normalize a file extension to the common form, making it lowercase and checking some synonyms, and ensure it's clean. More...
 
static normalizeTitle ( $title, $exception=false)
 Given a string or Title object return either a valid Title object with namespace NS_FILE or null. More...
 
static scaleHeight ( $srcWidth, $srcHeight, $dstWidth)
 Calculate the height of a thumbnail using the source and destination width. More...
 
static splitMime (?string $mime)
 Split an internet media type into its two components; if not a two-part name, set the minor type to 'unknown'. More...
 

Protected Member Functions

 getCacheFields ( $prefix='img_')
 Returns the list of object properties that are included as-is in the cache. More...
 
 getCacheKey ()
 Get the memcached key for the main data for this file, or false if there is no access to the shared cache. More...
 
 getLazyCacheFields ( $prefix='img_')
 Returns the list of object properties that are included as-is in the cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB(). More...
 
 getThumbnails ( $archiveName=false)
 getTransformScript inherited More...
 
 loadExtraFromDB ()
 Load lazy file metadata from the DB. More...
 
 loadFromDB ( $flags=0)
 Load file metadata from the DB. More...
 
 loadMetadataFromDbFieldValue (IDatabase $db, $metadataBlob)
 Unserialize a metadata blob which came from the database and store it in $this. More...
 
 loadMetadataFromString ( $metadataString)
 Unserialize a metadata string which came from some non-DB source, or is the return value of IDatabase::decodeBlob(). More...
 
 publishTo ( $src, $dstRel, $flags=0, array $options=[])
 Move or copy a file to a specified location. More...
 
 purgeThumbList ( $dir, $files)
 Delete a list of thumbnails visible at urls. More...
 
 readOnlyFatalStatus ()
 
 reserializeMetadata ()
 Write the metadata back to the database with the current serialization format. More...
 
 setProps ( $info)
 Set properties in this object to be equal to those given in the associative array $info. More...
 
 unprefixRow ( $row, $prefix='img_')
 
- Protected Member Functions inherited from File
 assertRepoDefined ()
 Assert that $this->repo is set to a valid FileRepo instance. More...
 
 assertTitleDefined ()
 Assert that $this->title is set to a Title. More...
 
 generateBucketsIfNeeded ( $params, $flags=0)
 Generates chained bucketed thumbnails if needed. More...
 
 getBucketThumbName ( $bucket)
 Returns the name of the thumb for a given bucket. More...
 
 getBucketThumbPath ( $bucket)
 Returns the repo path of the thumb for a given bucket. More...
 
 getCanRender ()
 Accessor for __get() More...
 
 getIsSafeFile ()
 Accessor for __get() More...
 
 getIsSafeFileUncached ()
 Uncached accessor. More...
 
 getRedirectedTitle ()
 
 getThumbnails ()
 Get all thumbnail names previously generated for this file STUB Overridden by LocalFile. More...
 
 isHashed ()
 
 isTrustedFile ()
 Returns true if the file is flagged as trusted. More...
 
 makeTransformTmpFile ( $thumbPath)
 Creates a temp FS file with the same extension and the thumbnail. More...
 
 migrateThumbFile ( $thumbName)
 Hook into transform() to allow migration of thumbnail files STUB. More...
 
 readOnlyError ()
 
 transformErrorOutput ( $thumbPath, $thumbUrl, $params, $flags)
 Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors) More...
 

Protected Attributes

int $bits
 Returned by getimagesize (loadFromXxx) More...
 
bool $dataLoaded = false
 Whether or not core data has been loaded from the database (loadFromXxx) More...
 
int $deleted
 Bitfield akin to rev_deleted. More...
 
bool $extraDataLoaded = false
 Whether or not lazy-loaded data has been loaded from the database. More...
 
bool $fileExists
 Does the file exist on disk? (loadFromXxx) More...
 
int $height
 Image height. More...
 
string $media_type
 MEDIATYPE_xxx (bitmap, drawing, audio...) More...
 
array $metadataArray = []
 Unserialized metadata. More...
 
string[] $metadataBlobs = []
 Map of metadata item name to blob address. More...
 
string null $metadataSerializationFormat
 One of the MDS_* constants, giving the format of the metadata as stored in the DB, or null if the data was not loaded from the DB. More...
 
string $mime
 MIME type, determined by MimeAnalyzer::guessMimeType. More...
 
string $repoClass = LocalRepo::class
 
string $sha1
 SHA-1 base 36 content hash. More...
 
int $size
 Size in bytes (loadFromXxx) More...
 
string[] $unloadedMetadataBlobs = []
 Map of metadata item name to blob address for items that exist but have not yet been loaded into $this->metadataArray. More...
 
int $width
 Image width. More...
 
- Protected Attributes inherited from File
bool $canRender
 Whether the output of transform() for this file is likely to be valid. More...
 
string $extension
 File extension. More...
 
FSFile bool $fsFile
 False if undefined. More...
 
MediaHandler $handler
 
string null $hashPath
 Relative path including trailing slash. More...
 
bool $isSafeFile
 Whether this media file is in a format that is unlikely to contain viruses or malicious content. More...
 
string $lastError
 Text of last error. More...
 
string null $name
 The name of a file from its title object. More...
 
int false $pageCount
 Number of pages of a multipage document, or false for documents which aren't multipage documents. More...
 
string $path
 The storage path corresponding to one of the zones. More...
 
string $redirected
 Main part of the title, with underscores (Title::getDBkey) More...
 
Title $redirectedTitle
 
Title $redirectTitle
 
string $repoClass = FileRepo::class
 Required Repository class type. More...
 
Title string bool $title
 
array $tmpBucketedThumbCache = []
 Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width. More...
 
string false $transformScript
 URL of transformscript (for example thumb.php) More...
 
string $url
 The URL corresponding to one of the four basic zones. More...
 

Additional Inherited Members

- Public Attributes inherited from File
FileRepo LocalRepo ForeignAPIRepo bool $repo
 Some member variables can be lazy-initialised using __get(). More...
 
const DELETE_SOURCE = 1
 
const DELETED_COMMENT = 2
 
const DELETED_FILE = 1
 
const DELETED_RESTRICTED = 8
 
const DELETED_USER = 4
 
const FOR_PUBLIC = 1
 
const FOR_THIS_USER = 2
 
const RAW = 3
 
const RENDER_FORCE = 2
 Force rendering even if thumbnail already exist and using RENDER_NOW I.e. More...
 
const RENDER_NOW = 1
 Force rendering in the current process. More...
 
const THUMB_FULL_NAME = 1
 
- Public Attributes inherited from IDBAccessObject
const READ_NONE = -1
 Constants for object loading bitfield flags (higher => higher QoS) More...
 

Detailed Description

Local file in the wiki's own database.

Provides methods to retrieve paths (physical, logical, URL), to generate image thumbnails or for uploading.

Note that only the repo object knows what its file class is called. You should never name a file class explicitly outside of the repo class. Instead use the repo's factory functions to generate file objects, for example:

RepoGroup::singleton()->getLocalRepo()->newFile( $title );

Consider the services container below;

$services = MediaWikiServices::getInstance();

The convenience services $services->getRepoGroup()->getLocalRepo()->newFile() and $services->getRepoGroup()->findFile() should be sufficient in most cases.

@TODO: DI - Instead of using MediaWikiServices::getInstance(), a service should ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile() and $this->repoGroup->getLocalRepo()->newFile().

Stability: stable
to extend

Definition at line 60 of file LocalFile.php.

Constructor & Destructor Documentation

◆ __construct()

LocalFile::__construct (   $title,
  $repo 
)

Do not call this except from inside a repo class.

Stability: stable
to call
Parameters
Title$title
LocalRepo$repo

Reimplemented from File.

Definition at line 319 of file LocalFile.php.

References File\$repo, File\$title, File\assertRepoDefined(), and File\assertTitleDefined().

◆ __destruct()

LocalFile::__destruct ( )

Clean up any dangling locks.

Definition at line 2682 of file LocalFile.php.

Member Function Documentation

◆ acquireFileLock()

LocalFile::acquireFileLock (   $timeout = 0)

Acquire an exclusive lock on the file, indicating an intention to write to the file backend.

Parameters
float | int$timeoutThe timeout in seconds
Returns
Status
Since
1.28

Definition at line 2585 of file LocalFile.php.

References LockManager\LOCK_EX, and Status\wrap().

◆ deleteFile()

LocalFile::deleteFile (   $reason,
UserIdentity  $user,
  $suppress = false 
)

Delete all versions of the file.

Since
1.35

Moves the files into an archive directory (or deletes them) and removes the database rows.

Cache purging is done; logging is caller's responsibility.

Stability: stable
to override
Parameters
string$reason
UserIdentity$user
bool$suppress
Returns
Status

Reimplemented from File.

Reimplemented in ForeignDBFile.

Definition at line 2313 of file LocalFile.php.

References DeferredUpdates\addUpdate(), and SiteStatsUpdate\factory().

◆ deleteOldFile()

LocalFile::deleteOldFile (   $archiveName,
  $reason,
UserIdentity  $user,
  $suppress = false 
)

Delete an old version of the file.

Since
1.35
Stability: stable
to override

Moves the file into an archive directory (or deletes it) and removes the database row.

Cache purging is done; logging is caller's responsibility.

Parameters
string$archiveName
string$reason
UserIdentity$user
bool$suppress
Exceptions
MWExceptionException on database or file store failure
Returns
Status

Definition at line 2374 of file LocalFile.php.

◆ exists()

LocalFile::exists ( )

canRender inherited

mustRender inherited allowInlineDisplay inherited isSafeFile inherited isTrustedFile inherited Returns true if the file exists on disk. @stable to override

Returns
bool Whether file exist on disk.

Reimplemented from File.

Reimplemented in OldLocalFile.

Definition at line 1297 of file LocalFile.php.

◆ getBitDepth()

LocalFile::getBitDepth ( )

@stable to override

Returns
int

Reimplemented from File.

Definition at line 1246 of file LocalFile.php.

◆ getCacheFields()

LocalFile::getCacheFields (   $prefix = 'img_')
protected

Returns the list of object properties that are included as-is in the cache.

Stability: stable
to override
Parameters
string$prefixMust be the empty string
Returns
string[]
Since
1.31 No longer accepts a non-empty $prefix

Reimplemented in OldLocalFile.

Definition at line 472 of file LocalFile.php.

Referenced by setProps().

◆ getCacheKey()

LocalFile::getCacheKey ( )
protected

Get the memcached key for the main data for this file, or false if there is no access to the shared cache.

Stability: stable
to override
Returns
string|bool

Reimplemented in OldLocalFile.

Definition at line 340 of file LocalFile.php.

References File\getName().

Referenced by getMutableCacheKeys(), and invalidateCache().

◆ getDescription()

LocalFile::getDescription (   $audience = self::FOR_PUBLIC,
Authority  $performer = null 
)
Stability: stable
to override
Parameters
int$audience
Authority | null$performer
Returns
string

Reimplemented from File.

Definition at line 2512 of file LocalFile.php.

Referenced by RevDelArchivedFileItem\getApiData(), and RevDelFileItem\getApiData().

◆ getDescriptionShortUrl()

LocalFile::getDescriptionShortUrl ( )

Get short description URL for a file based on the page ID.

@stable to override

Returns
string|null
Since
1.27

Reimplemented from File.

Reimplemented in ForeignDBFile.

Definition at line 1034 of file LocalFile.php.

References File\$url.

◆ getDescriptionText()

LocalFile::getDescriptionText ( Language  $lang = null)

Get the HTML text of the description page This is not used by ImagePage for local files, since (among other things) it skips the parser cache.

Stability: stable
to override
Parameters
Language | null$langWhat language to get description in (Optional)
Returns
string|false

Reimplemented from File.

Reimplemented in ForeignDBFile.

Definition at line 2458 of file LocalFile.php.

References $lang, RequestContext\getMain(), getTitle(), getUser(), ParserOptions\newFromContext(), and ParserOptions\newFromUserAndLang().

◆ getDescriptionTouched()

LocalFile::getDescriptionTouched ( )
Stability: stable
to override
Returns
bool|string

Reimplemented from File.

Definition at line 2537 of file LocalFile.php.

References wfTimestamp().

◆ getDescriptionUrl()

LocalFile::getDescriptionUrl ( )

isMultipage inherited

pageCount inherited scaleHeight inherited getImageSize inherited Get the URL of the file description page.

Stability: stable
to override
Returns
string|bool

Reimplemented from File.

Reimplemented in ForeignDBFile.

Definition at line 2441 of file LocalFile.php.

◆ getHeight()

LocalFile::getHeight (   $page = 1)

Return the height of the image @stable to override.

Parameters
int$page
Returns
int

Reimplemented from File.

Definition at line 1001 of file LocalFile.php.

References File\$handler, $height, File\getHandler(), MediaHandler\getPageDimensions(), File\isMultipage(), and load().

Referenced by RevDelArchivedFileItem\getApiData(), and RevDelFileItem\getApiData().

◆ getHistory()

LocalFile::getHistory (   $limit = null,
  $start = null,
  $end = null,
  $inc = true 
)

purgeDescription inherited

purgeEverything inherited

Stability: stable
to override
Parameters
int | null$limitOptional: Limit to number of results
string | int | null$startOptional: Timestamp, start from
string | int | null$endOptional: Timestamp, end at
bool$inc
Returns
OldLocalFile[]

Reimplemented from File.

Definition at line 1530 of file LocalFile.php.

References $dbr, $res, and OldLocalFile\getQueryInfo().

◆ getLazyCacheFields()

LocalFile::getLazyCacheFields (   $prefix = 'img_')
protected

Returns the list of object properties that are included as-is in the cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().

Parameters
string$prefixMust be the empty string
Returns
string[]
Since
1.31 No longer accepts a non-empty $prefix

Definition at line 494 of file LocalFile.php.

◆ getMediaType()

LocalFile::getMediaType ( )

Returns the type of the media in the file.

Use the value returned by this function with the MEDIATYPE_xxx constants. @stable to override

Returns
string

Reimplemented from File.

Definition at line 1280 of file LocalFile.php.

◆ getMetadata()

LocalFile::getMetadata ( )

Get handler-specific metadata as a serialized string.

Deprecated:
since 1.37 use getMetadataArray() or getMetadataItem()
Returns
string

Reimplemented from File.

Definition at line 1056 of file LocalFile.php.

References getMetadataArray(), and serialize().

◆ getMetadataArray()

LocalFile::getMetadataArray ( )

Get unserialized handler-specific metadata.

Since
1.37
Returns
array

Reimplemented from File.

Definition at line 1074 of file LocalFile.php.

References getMetadataItems().

Referenced by getMetadata().

◆ getMetadataForDb()

LocalFile::getMetadataForDb ( IDatabase  $db)

Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.

If metadata splitting is enabled, this may write blobs to the database, returning their addresses.

Definition at line 1124 of file LocalFile.php.

References $s, Wikimedia\Rdbms\IDatabase\encodeBlob(), and serialize().

Referenced by reserializeMetadata(), and upgradeRow().

◆ getMetadataItems()

LocalFile::getMetadataItems ( array  $itemNames)

Get multiple elements of the unserialized handler-specific metadata.

Since
1.37
Parameters
string[]$itemNames
Returns
array

Reimplemented from File.

Definition at line 1087 of file LocalFile.php.

Referenced by getMetadataArray().

◆ getMimeType()

LocalFile::getMimeType ( )

Returns the MIME type of the file.

@stable to override

Returns
string

Reimplemented from File.

Definition at line 1268 of file LocalFile.php.

References $mime.

◆ getMutableCacheKeys()

LocalFile::getMutableCacheKeys ( WANObjectCache  $cache)
Parameters
WANObjectCache$cache
Returns
string[]
Since
1.28

Definition at line 349 of file LocalFile.php.

References getCacheKey().

◆ getQueryInfo()

static LocalFile::getQueryInfo ( array  $options = [])
static

Return the tables, fields, and join conditions to be selected to create a new localfile object.

Since 1.34, img_user and img_user_text have not been present in the database, but they continue to be available in query results as aliases.

Since
1.31
Stability: stable
to override
Parameters
string[]$options
  • omit-lazy: Omit fields that are lazily cached.
Returns
array[] With three keys:
  • tables: (string[]) to include in the $table to IDatabase->select() or SelectQueryBuilder::tables
  • fields: (string[]) to include in the $vars to IDatabase->select() or SelectQueryBuilder::fields
  • joins: (array) to include in the $join_conds to IDatabase->select() or SelectQueryBuilder::joinConds

Reimplemented in OldLocalFile.

Definition at line 271 of file LocalFile.php.

Referenced by CheckImages\execute(), RefreshFileHeaders\execute(), RefreshImageMetadata\execute(), LocalRepo\findBySha1(), LocalRepo\findBySha1s(), LocalRepo\findFiles(), LocalRepo\findFilesByPrefix(), and SpecialMIMESearch\getQueryInfo().

◆ getRepo()

LocalFile::getRepo ( )
Returns
LocalRepo|bool

Reimplemented from File.

Reimplemented in ForeignDBFile.

Definition at line 330 of file LocalFile.php.

References File\$repo.

Referenced by LocalFileMoveBatch\__construct().

◆ getSha1()

LocalFile::getSha1 ( )
Stability: stable
to override
Returns
string|false

Reimplemented from File.

Definition at line 2561 of file LocalFile.php.

Referenced by RevertAction\onSubmit().

◆ getSize()

LocalFile::getSize ( )

Returns the size of the image file, in bytes @stable to override.

Returns
int

Reimplemented from File.

Definition at line 1257 of file LocalFile.php.

Referenced by RevDelArchivedFileItem\getApiData(), and RevDelFileItem\getApiData().

◆ getThumbnails()

LocalFile::getThumbnails (   $archiveName = false)
protected

getTransformScript inherited

getUnscaledThumb inherited thumbName inherited createThumb inherited transform inherited getHandler inherited iconThumb inherited getLastError inherited Get all thumbnail names previously generated for this file @stable to override

Parameters
string | bool$archiveNameName of an archive file, default false
Returns
array First element is the base dir, then files in that base dir.

Definition at line 1319 of file LocalFile.php.

References $file.

◆ getTimestamp()

LocalFile::getTimestamp ( )
Stability: stable
to override
Returns
bool|string

Reimplemented from File.

Definition at line 2527 of file LocalFile.php.

Referenced by RevDelArchivedFileItem\getApiData(), RevDelFileItem\getApiData(), and upgradeRow().

◆ getUpgraded()

LocalFile::getUpgraded ( )
Returns
bool Whether upgradeRow() ran for this object

Definition at line 801 of file LocalFile.php.

◆ getUploader()

LocalFile::getUploader ( int  $audience = self::FOR_PUBLIC,
Authority  $performer = null 
)
Since
1.37
Stability: stable
to override
Parameters
int$audience
Authority | null$performer
Returns
UserIdentity|null

Reimplemented from File.

Definition at line 2495 of file LocalFile.php.

Referenced by RevDelArchivedFileItem\getApiData(), and RevDelFileItem\getApiData().

◆ getWidth()

LocalFile::getWidth (   $page = 1)

Return the width of the image @stable to override.

Parameters
int$page
Returns
int

Reimplemented from File.

Definition at line 968 of file LocalFile.php.

References File\$handler, $width, File\getHandler(), MediaHandler\getPageDimensions(), File\isMultipage(), and load().

Referenced by RevDelArchivedFileItem\getApiData(), and RevDelFileItem\getApiData().

◆ invalidateCache()

LocalFile::invalidateCache ( )

Purge the file object/metadata cache.

Definition at line 439 of file LocalFile.php.

References getCacheKey().

Referenced by upgradeRow().

◆ isCacheable()

LocalFile::isCacheable ( )
Returns
bool Whether to cache in RepoGroup (this avoids OOMs)

Reimplemented from File.

Definition at line 2569 of file LocalFile.php.

References serialize().

◆ isMissing()

LocalFile::isMissing ( )

splitMime inherited

getName inherited getTitle inherited getURL inherited getViewURL inherited getPath inherited isVisible inherited Checks if this file exists in its parent repo, as referenced by its virtual URL. @stable to override

Returns
bool

Reimplemented from File.

Definition at line 952 of file LocalFile.php.

References $fileExists, and File\getVirtualUrl().

◆ load()

LocalFile::load (   $flags = 0)

Load file metadata from cache or DB, unless already loaded.

Stability: stable
to override
Parameters
int$flags

Reimplemented from File.

Definition at line 729 of file LocalFile.php.

References loadExtraFromDB(), and loadFromDB().

Referenced by getHeight(), and getWidth().

◆ loadExtraFromDB()

LocalFile::loadExtraFromDB ( )
protected

Load lazy file metadata from the DB.

This covers fields that are sometimes not cached. @stable to override

Reimplemented in OldLocalFile.

Definition at line 543 of file LocalFile.php.

References loadMetadataFromDbFieldValue().

Referenced by load().

◆ loadFromDB()

LocalFile::loadFromDB (   $flags = 0)
protected

Load file metadata from the DB.

Stability: stable
to override
Parameters
int$flags

Reimplemented in OldLocalFile.

Definition at line 510 of file LocalFile.php.

References $dbr, File\getName(), and loadFromRow().

Referenced by load().

◆ loadFromFile()

LocalFile::loadFromFile (   $path = null)

Load metadata from the file itself.

Access: internal
Parameters
string | null$pathThe path or virtual URL to load from, or null to use the previously stored file.

Definition at line 460 of file LocalFile.php.

References File\$path, File\getVirtualUrl(), and setProps().

Referenced by upgradeRow().

◆ loadFromRow()

LocalFile::loadFromRow (   $row,
  $prefix = 'img_' 
)

Load file metadata from a DB result row.

Stability: stable
to override

Passing arbitrary fields in the row and expecting them to be translated to property names on $this is deprecated since 1.37. Instead, override loadFromRow(), and clone and unset the extra fields before passing them to the parent.

After the deprecation period has passed, extra fields will be ignored, and the deprecation warning will be removed.

Parameters
stdClass$row
string$prefix

Reimplemented in OldLocalFile.

Definition at line 651 of file LocalFile.php.

References loadMetadataFromDbFieldValue(), unprefixRow(), wfDeprecatedMsg(), and wfTimestamp().

Referenced by loadFromDB().

◆ loadMetadataFromDbFieldValue()

LocalFile::loadMetadataFromDbFieldValue ( IDatabase  $db,
  $metadataBlob 
)
protected

Unserialize a metadata blob which came from the database and store it in $this.

Since
1.37
Parameters
IDatabase$db
string | Blob$metadataBlob

Definition at line 1192 of file LocalFile.php.

References Wikimedia\Rdbms\IDatabase\decodeBlob().

Referenced by loadExtraFromDB(), and loadFromRow().

◆ loadMetadataFromString()

LocalFile::loadMetadataFromString (   $metadataString)
protected

Unserialize a metadata string which came from some non-DB source, or is the return value of IDatabase::decodeBlob().

Since
1.37
Parameters
string$metadataString

Definition at line 1203 of file LocalFile.php.

References unserialize().

Referenced by setProps().

◆ lock()

LocalFile::lock ( )

Start an atomic DB section and lock the image for update or increments a reference counter if the lock is already held.

This method should not be used outside of LocalFile/LocalFile*Batch

Deprecated:
since 1.38 Use acquireFileLock()
Exceptions
LocalFileLockErrorThrows an error if the lock was not acquired
Returns
bool Whether the file lock owns/spawned the DB transaction

Definition at line 2613 of file LocalFile.php.

◆ maybeUpgradeRow()

LocalFile::maybeUpgradeRow ( )

◆ move()

LocalFile::move (   $target)

getLinksTo inherited

getExifData inherited isLocal inherited wasDeleted inherited Move file to the new title

Move current, old version and all thumbnails to the new filename. Old file is deleted.

Cache purging is done; checks for validity and logging are caller's responsibility

Stability: stable
to override
Parameters
Title$targetNew file name
Returns
Status

Reimplemented from File.

Reimplemented in ForeignDBFile.

Definition at line 2248 of file LocalFile.php.

References DeferredUpdates\addUpdate(), and wfDebugLog().

◆ newFromKey()

static LocalFile::newFromKey (   $sha1,
  $repo,
  $timestamp = false 
)
static

Create a LocalFile from a SHA-1 key Do not call this except from inside a repo class.

Stability: stable
to override
Parameters
string$sha1Base-36 SHA-1
LocalRepo$repo
string | bool$timestampMW_timestamp (optional)
Returns
bool|LocalFile

Reimplemented in OldLocalFile.

Definition at line 233 of file LocalFile.php.

References $dbr, File\$repo, and $sha1.

◆ newFromRow()

static LocalFile::newFromRow (   $row,
  $repo 
)
static

Create a LocalFile from a title Do not call this except from inside a repo class.

Stability: stable
to override
Parameters
stdClass$row
LocalRepo$repo
Returns
static

Reimplemented in OldLocalFile.

Definition at line 214 of file LocalFile.php.

References $file, File\$repo, File\$title, Title\makeTitle(), and NS_FILE.

◆ newFromTitle()

static LocalFile::newFromTitle (   $title,
  $repo,
  $unused = null 
)
static

Create a LocalFile from a title Do not call this except from inside a repo class.

Note: $unused param is only here to avoid an E_STRICT

Stability: stable
to override
Parameters
Title$title
LocalRepo$repo
null$unused
Returns
static

Reimplemented in OldLocalFile.

Definition at line 199 of file LocalFile.php.

References File\$repo, and File\$title.

◆ nextHistoryLine()

LocalFile::nextHistoryLine ( )

Returns the history of this file, line by line.

starts with current version, then old versions. uses $this->historyLine to check which line to return: 0 return line for current version 1 query for old versions, return first one 2, ... return next old version from above query

Stability: stable
to override
Returns
stdClass|bool

Reimplemented from File.

Definition at line 1589 of file LocalFile.php.

References $dbr, and OldLocalFile\getQueryInfo().

◆ prerenderThumbnails()

LocalFile::prerenderThumbnails ( )

Prerenders a configurable set of thumbnails.

Stability: stable
to override
Since
1.28

Definition at line 1446 of file LocalFile.php.

References getTitle().

◆ publish()

LocalFile::publish (   $src,
  $flags = 0,
array  $options = [] 
)

Move or copy a file to its public location.

If a file exists at the destination, move it to an archive. Returns a Status object with the archive name in the "value" member on success.

The archive name should be passed through to recordUpload for database registration.

Stability: stable
to override
Parameters
string | FSFile$srcLocal filesystem path or virtual URL to the source image
int$flagsA bitwise combination of: File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
array$optionsOptional additional parameters
Returns
Status On success, the value member contains the archive name, or an empty string if it was a new file.

Reimplemented from File.

Reimplemented in ForeignDBFile.

Definition at line 2158 of file LocalFile.php.

◆ publishTo()

LocalFile::publishTo (   $src,
  $dstRel,
  $flags = 0,
array  $options = [] 
)
protected

Move or copy a file to a specified location.

Returns a Status object with the archive name in the "value" member on success.

The archive name should be passed through to recordUpload for database registration.

Stability: stable
to override
Parameters
string | FSFile$srcLocal filesystem path or virtual URL to the source image
string$dstRelTarget relative path
int$flagsA bitwise combination of: File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
array$optionsOptional additional parameters
Returns
Status On success, the value member contains the archive name, or an empty string if it was a new file.

Definition at line 2178 of file LocalFile.php.

References File\DELETE_SOURCE, FileRepo\DELETE_SOURCE, FSFile\getSha1Base36FromPath(), FileRepo\isVirtualUrl(), and wfTimestamp().

◆ purgeCache()

LocalFile::purgeCache (   $options = [])

Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.

Stability: stable
to override
Parameters
array$optionsAn array potentially with the key forThumbRefresh.
Note
This used to purge old thumbnails by default as well, but doesn't anymore.

Reimplemented from File.

Definition at line 1356 of file LocalFile.php.

◆ purgeOldThumbnails()

LocalFile::purgeOldThumbnails (   $archiveName)

Delete cached transformed files for an archived version only.

Stability: stable
to override
Parameters
string$archiveNameName of the archived file

Definition at line 1379 of file LocalFile.php.

Referenced by PurgeChangedFiles\purgeFromArchiveTable().

◆ purgeThumbList()

LocalFile::purgeThumbList (   $dir,
  $files 
)
protected

Delete a list of thumbnails visible at urls.

Stability: stable
to override
Parameters
string$dirBase dir of the files.
array$filesArray of strings: relative filenames (to $dir)

Definition at line 1489 of file LocalFile.php.

References $file, and wfDebug().

◆ purgeThumbnails()

LocalFile::purgeThumbnails (   $options = [])

Delete cached transformed files for the current version only.

Stability: stable
to override
Parameters
array$options

Definition at line 1406 of file LocalFile.php.

◆ readOnlyFatalStatus()

LocalFile::readOnlyFatalStatus ( )
protected
Returns
Status

Definition at line 2674 of file LocalFile.php.

◆ recordUpload3()

LocalFile::recordUpload3 ( string  $oldver,
string  $comment,
string  $pageText,
Authority  $performer,
  $props = false,
  $timestamp = false,
  $tags = [],
bool  $createNullRevision = true,
bool  $revert = false 
)

Record a file upload in the upload log and the image table (version 3)

Since
1.35
Stability: stable
to override
Parameters
string$oldver
string$comment
string$pageText
Authority$performer
bool | array$props
string | bool$timestamp
string[]$tags
bool$createNullRevisionSet to false to avoid creation of a null revision on file upload, see T193621
bool$revertIf this file upload is a revert
Returns
Status

Definition at line 1781 of file LocalFile.php.

◆ releaseFileLock()

LocalFile::releaseFileLock ( )

Release a lock acquired with acquireFileLock().

Returns
Status
Since
1.28

Definition at line 2597 of file LocalFile.php.

References LockManager\LOCK_EX, and Status\wrap().

◆ reserializeMetadata()

LocalFile::reserializeMetadata ( )
protected

Write the metadata back to the database with the current serialization format.

Reimplemented in OldLocalFile.

Definition at line 857 of file LocalFile.php.

References getMetadataForDb().

Referenced by maybeUpgradeRow().

◆ resetHistory()

LocalFile::resetHistory ( )

Reset the history pointer to the first element of the history.

Stability: stable
to override

Reimplemented from File.

Definition at line 1637 of file LocalFile.php.

◆ restore()

LocalFile::restore (   $versions = [],
  $unsuppress = false 
)

Restore all or specified deleted revisions to the given file.

Permissions and logging are left to the caller.

May throw database exceptions on error.

Stability: stable
to override
Parameters
int[]$versionsSet of record ids of deleted items to restore, or empty to restore all revisions.
bool$unsuppress
Returns
Status

Reimplemented from File.

Reimplemented in ForeignDBFile.

Definition at line 2408 of file LocalFile.php.

◆ setProps()

LocalFile::setProps (   $info)
protected

Set properties in this object to be equal to those given in the associative array $info.

Only cacheable fields can be set. All fields must be set in $info except for getLazyCacheFields().

If 'mime' is given, it will be split into major_mime/minor_mime. If major_mime/minor_mime are given, $this->mime will also be set.

@stable to override

Parameters
array$info

Definition at line 885 of file LocalFile.php.

References getCacheFields(), loadMetadataFromString(), and File\splitMime().

Referenced by loadFromFile().

◆ unlock()

LocalFile::unlock ( )

Decrement the lock reference count and end the atomic section if it reaches zero.

This method should not be used outside of LocalFile/LocalFile*Batch

The commit and lock release will happen when no atomic sections are active, which may happen immediately or at some point after calling this

Deprecated:
since 1.38 Use releaseFileLock()

Definition at line 2660 of file LocalFile.php.

◆ unprefixRow()

LocalFile::unprefixRow (   $row,
  $prefix = 'img_' 
)
protected
Parameters
array | stdClass$row
string$prefix
Exceptions
MWException
Returns
array

Definition at line 619 of file LocalFile.php.

References File\$name.

Referenced by loadFromRow().

◆ upgradeRow()

LocalFile::upgradeRow ( )

Fix assorted version-related problems with the image row by reloading it from the file.

Stability: stable
to override

Reimplemented from File.

Reimplemented in OldLocalFile.

Definition at line 809 of file LocalFile.php.

References getMetadataForDb(), File\getName(), getTimestamp(), invalidateCache(), loadFromFile(), File\splitMime(), and wfDebug().

Referenced by maybeUpgradeRow().

◆ upload()

LocalFile::upload (   $src,
  $comment,
  $pageText,
  $flags = 0,
  $props = false,
  $timestamp = false,
Authority  $uploader = null,
  $tags = [],
  $createNullRevision = true,
  $revert = false 
)

getHashPath inherited

getRel inherited getUrlRel inherited getArchiveRel inherited getArchivePath inherited getThumbPath inherited getArchiveUrl inherited getThumbUrl inherited getArchiveVirtualUrl inherited getThumbVirtualUrl inherited isHashed inherited Upload a file and record it in the DB

Parameters
string | FSFile$srcSource storage path, virtual URL, or filesystem path
string$commentUpload description
string$pageTextText to use for the new description page, if a new description page is created
int | bool$flagsFlags for publish()
array | bool$propsFile properties, if known. This can be used to reduce the upload time when uploading virtual URLs for which the file info is already known
string | bool$timestampTimestamp for img_timestamp, or false to use the current time
Authority | null$uploaderobject or null to use the context authority
string[]$tagsChange tags to add to the log entry and page revision. (This doesn't check $uploader's permissions.)
bool$createNullRevisionSet to false to avoid creation of a null revision on file upload, see T193621
bool$revertIf this file upload is a revert
Returns
Status On success, the value member contains the archive name, or an empty string if it was a new file.

Definition at line 1678 of file LocalFile.php.

References MediaHandler\getHandler(), RequestContext\getMain(), FileBackend\isStoragePath(), FileRepo\isVirtualUrl(), and unserialize().

Member Data Documentation

◆ $bits

int LocalFile::$bits
protected

Returned by getimagesize (loadFromXxx)

Definition at line 90 of file LocalFile.php.

◆ $dataLoaded

bool LocalFile::$dataLoaded = false
protected

Whether or not core data has been loaded from the database (loadFromXxx)

Definition at line 127 of file LocalFile.php.

◆ $deleted

int LocalFile::$deleted
protected

Bitfield akin to rev_deleted.

Definition at line 133 of file LocalFile.php.

◆ $extraDataLoaded

bool LocalFile::$extraDataLoaded = false
protected

Whether or not lazy-loaded data has been loaded from the database.

Definition at line 130 of file LocalFile.php.

◆ $fileExists

bool LocalFile::$fileExists
protected
Initial value:
=
private const MAX_PAGE_RENDER_JOBS 50

Does the file exist on disk? (loadFromXxx)

Definition at line 81 of file LocalFile.php.

Referenced by isMissing().

◆ $height

int LocalFile::$height
protected

Image height.

Definition at line 87 of file LocalFile.php.

Referenced by getHeight().

◆ $media_type

string LocalFile::$media_type
protected

MEDIATYPE_xxx (bitmap, drawing, audio...)

Definition at line 93 of file LocalFile.php.

◆ $metadataArray

array LocalFile::$metadataArray = []
protected

Unserialized metadata.

Definition at line 102 of file LocalFile.php.

◆ $metadataBlobs

string [] LocalFile::$metadataBlobs = []
protected

Map of metadata item name to blob address.

Definition at line 113 of file LocalFile.php.

◆ $metadataSerializationFormat

string null LocalFile::$metadataSerializationFormat
protected

One of the MDS_* constants, giving the format of the metadata as stored in the DB, or null if the data was not loaded from the DB.

Definition at line 110 of file LocalFile.php.

◆ $mime

string LocalFile::$mime
protected

MIME type, determined by MimeAnalyzer::guessMimeType.

Definition at line 96 of file LocalFile.php.

◆ $repoClass

string LocalFile::$repoClass = LocalRepo::class
protected

Definition at line 136 of file LocalFile.php.

◆ $sha1

string LocalFile::$sha1
protected

SHA-1 base 36 content hash.

Definition at line 124 of file LocalFile.php.

Referenced by newFromKey(), and OldLocalFile\newFromKey().

◆ $size

int LocalFile::$size
protected

Size in bytes (loadFromXxx)

Definition at line 99 of file LocalFile.php.

◆ $unloadedMetadataBlobs

string [] LocalFile::$unloadedMetadataBlobs = []
protected

Map of metadata item name to blob address for items that exist but have not yet been loaded into $this->metadataArray.

Definition at line 121 of file LocalFile.php.

◆ $width

int LocalFile::$width
protected

Image width.

Definition at line 84 of file LocalFile.php.

Referenced by getWidth().


The documentation for this class was generated from the following file: