3 * @defgroup FileRepo File Repository
5 * @brief This module handles how MediaWiki interacts with filesystems.
10 use MediaWiki\Context\RequestContext
;
11 use MediaWiki\Linker\LinkTarget
;
12 use MediaWiki\MainConfigNames
;
13 use MediaWiki\MediaWikiServices
;
14 use MediaWiki\Page\PageIdentity
;
15 use MediaWiki\Permissions\Authority
;
16 use MediaWiki\Status\Status
;
17 use MediaWiki\Title\Title
;
18 use MediaWiki\User\UserIdentity
;
19 use MediaWiki\Utils\MWTimestamp
;
20 use Shellbox\Command\BoxedCommand
;
21 use Wikimedia\AtEase\AtEase
;
22 use Wikimedia\FileBackend\FileBackend
;
23 use Wikimedia\FileBackend\FSFile\FSFile
;
24 use Wikimedia\FileBackend\FSFile\TempFSFile
;
25 use Wikimedia\ObjectCache\WANObjectCache
;
26 use Wikimedia\Rdbms\IDBAccessObject
;
29 * Base code for file repositories.
31 * This program is free software; you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation; either version 2 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License along
42 * with this program; if not, write to the Free Software Foundation, Inc.,
43 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
44 * http://www.gnu.org/copyleft/gpl.html
51 * Base class for file repositories
53 * See [the architecture doc](@ref filerepoarch) for more information.
58 public const DELETE_SOURCE
= 1;
59 public const OVERWRITE
= 2;
60 public const OVERWRITE_SAME
= 4;
61 public const SKIP_LOCKING
= 8;
63 public const NAME_AND_TIME_ONLY
= 1;
65 /** @var bool Whether to fetch commons image description pages and display
66 * them on the local wiki
68 public $fetchDescription;
71 public $descriptionCacheExpiry;
74 protected $hasSha1Storage = false;
77 protected $supportsSha1URLs = false;
79 /** @var FileBackend */
82 /** @var array Map of zones to config */
83 protected $zones = [];
85 /** @var string URL of thumb.php */
86 protected $thumbScriptUrl;
88 /** @var bool Whether to skip media file transformation on parse and rely
89 * on a 404 handler instead.
91 protected $transformVia404;
93 /** @var string|null URL of image description pages, e.g.
94 * https://en.wikipedia.org/wiki/File:
96 protected $descBaseUrl;
98 /** @var string|null URL of the MediaWiki installation, equivalent to
99 * $wgScriptPath, e.g. https://en.wikipedia.org/w
101 protected $scriptDirUrl;
103 /** @var string|null Equivalent to $wgArticlePath, e.g. https://en.wikipedia.org/wiki/$1 */
104 protected $articleUrl;
106 /** @var bool Equivalent to $wgCapitalLinks (or $wgCapitalLinkOverrides[NS_FILE],
107 * determines whether filenames implicitly start with a capital letter.
108 * The current implementation may give incorrect description page links
109 * when the local $wgCapitalLinks and initialCapital are mismatched.
111 protected $initialCapital;
113 /** @var string May be 'paranoid' to remove all parameters from error
114 * messages, 'none' to leave the paths in unchanged, or 'simple' to
115 * replace paths with placeholders. Default for LocalRepo is
118 protected $pathDisclosureProtection = 'simple';
120 /** @var string|false Public zone URL. */
123 /** @var string|false The base thumbnail URL. Defaults to "<url>/thumb". */
126 /** @var int The number of directory levels for hash-based division of files */
127 protected $hashLevels;
129 /** @var int The number of directory levels for hash-based division of deleted files */
130 protected $deletedHashLevels;
132 /** @var int File names over this size will use the short form of thumbnail
133 * names. Short thumbnail names only have the width, parameters, and the
136 protected $abbrvThreshold;
138 /** @var null|string The URL to a favicon (optional, may be a server-local path URL). */
139 protected $favicon = null;
141 /** @var bool Whether all zones should be private (e.g. private wiki repo) */
142 protected $isPrivate;
144 /** @var callable Override these in the base class */
145 protected $fileFactory = [ UnregisteredLocalFile
::class, 'newFromTitle' ];
146 /** @var callable|false Override these in the base class */
147 protected $oldFileFactory = false;
148 /** @var callable|false Override these in the base class */
149 protected $fileFactoryKey = false;
150 /** @var callable|false Override these in the base class */
151 protected $oldFileFactoryKey = false;
153 /** @var string URL of where to proxy thumb.php requests to.
154 * Example: http://127.0.0.1:8888/wiki/dev/thumb/
156 protected $thumbProxyUrl;
157 /** @var string Secret key to pass as an X-Swift-Secret header to the proxied thumb service */
158 protected $thumbProxySecret;
160 /** @var bool Disable local image scaling */
161 protected $disableLocalTransform = false;
163 /** @var WANObjectCache */
168 * @note Use $this->getName(). Public for back-compat only
169 * @todo make protected
174 * @see Documentation of info options at $wgLocalFileRepo
175 * @param array|null $info
176 * @phan-assert array $info
178 public function __construct( ?
array $info = null ) {
179 // Verify required settings presence
182 ||
!array_key_exists( 'name', $info )
183 ||
!array_key_exists( 'backend', $info )
185 throw new InvalidArgumentException( __CLASS__
.
186 " requires an array of options having both 'name' and 'backend' keys.\n" );
190 $this->name
= $info['name'];
191 if ( $info['backend'] instanceof FileBackend
) {
192 $this->backend
= $info['backend']; // useful for testing
195 MediaWikiServices
::getInstance()->getFileBackendGroup()->get( $info['backend'] );
198 // Optional settings that can have no value
199 $optionalSettings = [
200 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
201 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
202 'favicon', 'thumbProxyUrl', 'thumbProxySecret', 'disableLocalTransform'
204 foreach ( $optionalSettings as $var ) {
205 if ( isset( $info[$var] ) ) {
206 $this->$var = $info[$var];
210 // Optional settings that have a default
212 MediaWikiServices
::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE
);
213 $this->initialCapital
= $info['initialCapital'] ??
$localCapitalLinks;
214 if ( $localCapitalLinks && !$this->initialCapital
) {
215 // If the local wiki's file namespace requires an initial capital, but a foreign file
216 // repo doesn't, complications will result. Linker code will want to auto-capitalize the
217 // first letter of links to files, but those links might actually point to files on
218 // foreign wikis with initial-lowercase names. This combination is not likely to be
219 // used by anyone anyway, so we just outlaw it to save ourselves the bugs. If you want
220 // to include a foreign file repo with initialCapital false, set your local file
221 // namespace to not be capitalized either.
222 throw new InvalidArgumentException(
223 'File repos with initial capital false are not allowed on wikis where the File ' .
224 'namespace has initial capital true' );
227 $this->url
= $info['url'] ??
false; // a subclass may set the URL (e.g. ForeignAPIRepo)
228 $defaultThumbUrl = $this->url ?
$this->url
. '/thumb' : false;
229 $this->thumbUrl
= $info['thumbUrl'] ??
$defaultThumbUrl;
230 $this->hashLevels
= $info['hashLevels'] ??
2;
231 $this->deletedHashLevels
= $info['deletedHashLevels'] ??
$this->hashLevels
;
232 $this->transformVia404
= !empty( $info['transformVia404'] );
233 $this->abbrvThreshold
= $info['abbrvThreshold'] ??
255;
234 $this->isPrivate
= !empty( $info['isPrivate'] );
235 // Give defaults for the basic zones...
236 $this->zones
= $info['zones'] ??
[];
237 foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) {
238 if ( !isset( $this->zones
[$zone]['container'] ) ) {
239 $this->zones
[$zone]['container'] = "{$this->name}-{$zone}";
241 if ( !isset( $this->zones
[$zone]['directory'] ) ) {
242 $this->zones
[$zone]['directory'] = '';
244 if ( !isset( $this->zones
[$zone]['urlsByExt'] ) ) {
245 $this->zones
[$zone]['urlsByExt'] = [];
249 $this->supportsSha1URLs
= !empty( $info['supportsSha1URLs'] );
251 $this->wanCache
= $info['wanCache'] ?? WANObjectCache
::newEmpty();
255 * Get the file backend instance. Use this function wisely.
257 * @return FileBackend
259 public function getBackend() {
260 return $this->backend
;
264 * Get an explanatory message if this repo is read-only.
265 * This checks if an administrator disabled writes to the backend.
267 * @return string|false Returns false if the repo is not read-only
269 public function getReadOnlyReason() {
270 return $this->backend
->getReadOnlyReason();
274 * Ensure that a single zone or list of zones is defined for usage
276 * @param string[]|string $doZones Only do a particular zones
278 protected function initZones( $doZones = [] ): void
{
279 foreach ( (array)$doZones as $zone ) {
280 $root = $this->getZonePath( $zone );
281 if ( $root === null ) {
282 throw new RuntimeException( "No '$zone' zone defined in the {$this->name} repo." );
288 * Determine if a string is an mwrepo:// URL
293 public static function isVirtualUrl( $url ) {
294 return str_starts_with( $url, 'mwrepo://' );
298 * Get a URL referring to this repository, with the private mwrepo protocol.
299 * The suffix, if supplied, is considered to be unencoded, and will be
300 * URL-encoded before being returned.
302 * @param string|false $suffix
305 public function getVirtualUrl( $suffix = false ) {
306 $path = 'mwrepo://' . $this->name
;
307 if ( $suffix !== false ) {
308 $path .= '/' . rawurlencode( $suffix );
315 * Get the URL corresponding to one of the four basic zones
317 * @param string $zone One of: public, deleted, temp, thumb
318 * @param string|null $ext Optional file extension
319 * @return string|false
321 public function getZoneUrl( $zone, $ext = null ) {
322 if ( in_array( $zone, [ 'public', 'thumb', 'transcoded' ] ) ) {
323 // standard public zones
324 if ( $ext !== null && isset( $this->zones
[$zone]['urlsByExt'][$ext] ) ) {
325 // custom URL for extension/zone
326 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
327 return $this->zones
[$zone]['urlsByExt'][$ext];
328 } elseif ( isset( $this->zones
[$zone]['url'] ) ) {
329 // custom URL for zone
330 return $this->zones
[$zone]['url'];
338 return false; // no public URL
340 return $this->thumbUrl
;
342 return "{$this->url}/transcoded";
349 * @return bool Whether non-ASCII path characters are allowed
351 public function backendSupportsUnicodePaths() {
352 return (bool)( $this->getBackend()->getFeatures() & FileBackend
::ATTR_UNICODE_PATHS
);
356 * Get the backend storage path corresponding to a virtual URL. Callers are responsible of
357 * verifying that $url is a valid virtual URL.
358 * Use this function wisely.
363 public function resolveVirtualUrl( $url ) {
364 if ( !str_starts_with( $url, 'mwrepo://' ) ) {
365 throw new InvalidArgumentException( __METHOD__
. ': unknown protocol' );
367 $bits = explode( '/', substr( $url, 9 ), 3 );
368 if ( count( $bits ) != 3 ) {
369 throw new InvalidArgumentException( __METHOD__
. ": invalid mwrepo URL: $url" );
371 [ $repo, $zone, $rel ] = $bits;
372 if ( $repo !== $this->name
) {
373 throw new InvalidArgumentException( __METHOD__
. ": fetching from a foreign repo is not supported" );
375 $base = $this->getZonePath( $zone );
377 throw new InvalidArgumentException( __METHOD__
. ": invalid zone: $zone" );
380 return $base . '/' . rawurldecode( $rel );
384 * The storage container and base path of a zone
386 * @param string $zone
387 * @return array (container, base path) or (null, null)
389 protected function getZoneLocation( $zone ) {
390 if ( !isset( $this->zones
[$zone] ) ) {
391 return [ null, null ]; // bogus
394 return [ $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] ];
398 * Get the storage path corresponding to one of the zones
400 * @param string $zone
401 * @return string|null Returns null if the zone is not defined
403 public function getZonePath( $zone ) {
404 [ $container, $base ] = $this->getZoneLocation( $zone );
405 if ( $container === null ||
$base === null ) {
408 $backendName = $this->backend
->getName();
409 if ( $base != '' ) { // may not be set
413 return "mwstore://$backendName/{$container}{$base}";
417 * Create a new File object from the local repository
419 * @param PageIdentity|LinkTarget|string $title
420 * @param string|false $time Time at which the image was uploaded. If this
421 * is specified, the returned object will be an instance of the
422 * repository's old file class instead of a current file. Repositories
423 * not supporting version control should return false if this parameter
425 * @return File|null A File, or null if passed an invalid Title
427 public function newFile( $title, $time = false ) {
428 $title = File
::normalizeTitle( $title );
433 if ( $this->oldFileFactory
) {
434 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
439 return call_user_func( $this->fileFactory
, $title, $this );
444 * Find an instance of the named file created at the specified time
445 * Returns false if the file does not exist. Repositories not supporting
446 * version control should return false if the time is specified.
448 * @param PageIdentity|LinkTarget|string $title
449 * @param array $options Associative array of options:
450 * time: requested time for a specific file version, or false for the
451 * current version. An image object will be returned which was
452 * created at the specified time (which may be archived or current).
453 * ignoreRedirect: If true, do not follow file redirects
454 * private: If an Authority object, return restricted (deleted) files if the
455 * performer is allowed to view them. Otherwise, such files will not
456 * be found. If set and not an Authority object, throws an exception.
457 * Authority is only accepted since 1.37, User was required before.
458 * latest: If true, load from the latest available data into File objects
459 * @return File|false False on failure
460 * @throws InvalidArgumentException
462 public function findFile( $title, $options = [] ) {
463 if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority
) ) {
464 throw new InvalidArgumentException(
465 __METHOD__
. ' called with the `private` option set to something ' .
466 'other than an Authority object'
470 $title = File
::normalizeTitle( $title );
474 if ( isset( $options['bypassCache'] ) ) {
475 $options['latest'] = $options['bypassCache']; // b/c
477 $time = $options['time'] ??
false;
478 $flags = !empty( $options['latest'] ) ? IDBAccessObject
::READ_LATEST
: 0;
479 # First try the current version of the file to see if it precedes the timestamp
480 $img = $this->newFile( $title );
484 $img->load( $flags );
485 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
488 # Now try an old version of the file
489 if ( $time !== false ) {
490 $img = $this->newFile( $title, $time );
492 $img->load( $flags );
493 if ( $img->exists() ) {
494 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
495 return $img; // always OK
497 // If its not empty, its an Authority object
498 !empty( $options['private'] ) &&
499 $img->userCan( File
::DELETED_FILE
, $options['private'] )
508 if ( !empty( $options['ignoreRedirect'] ) ) {
511 $redir = $this->checkRedirect( $title );
512 if ( $redir && $title->getNamespace() === NS_FILE
) {
513 $img = $this->newFile( $redir );
517 $img->load( $flags );
518 if ( $img->exists() ) {
519 $img->redirectedFrom( $title->getDBkey() );
529 * Find many files at once.
531 * @param array $items An array of titles, or an array of findFile() options with
532 * the "title" option giving the title. Example:
534 * $findItem = [ 'title' => $title, 'private' => true ];
535 * $findBatch = [ $findItem ];
536 * $repo->findFiles( $findBatch );
538 * No title should appear in $items twice, as the result use titles as keys
539 * @param int $flags Supports:
540 * - FileRepo::NAME_AND_TIME_ONLY : return a (search title => (title,timestamp)) map.
541 * The search title uses the input titles; the other is the final post-redirect title.
542 * All titles are returned as string DB keys and the inner array is associative.
543 * @return array Map of (file name => File objects) for matches or (search title => (title,timestamp))
545 public function findFiles( array $items, $flags = 0 ) {
547 foreach ( $items as $item ) {
548 if ( is_array( $item ) ) {
549 $title = $item['title'];
551 unset( $options['title'] );
554 !empty( $options['private'] ) &&
555 !( $options['private'] instanceof Authority
)
557 $options['private'] = RequestContext
::getMain()->getAuthority();
563 $file = $this->findFile( $title, $options );
565 $searchName = File
::normalizeTitle( $title )->getDBkey(); // must be valid
566 if ( $flags & self
::NAME_AND_TIME_ONLY
) {
567 $result[$searchName] = [
568 'title' => $file->getTitle()->getDBkey(),
569 'timestamp' => $file->getTimestamp()
572 $result[$searchName] = $file;
581 * Find an instance of the file with this key, created at the specified time
582 * Returns false if the file does not exist. Repositories not supporting
583 * version control should return false if the time is specified.
585 * @param string $sha1 Base 36 SHA-1 hash
586 * @param array $options Option array, same as findFile().
587 * @return File|false False on failure
588 * @throws InvalidArgumentException if the `private` option is set and not an Authority object
590 public function findFileFromKey( $sha1, $options = [] ) {
591 if ( !empty( $options['private'] ) && !( $options['private'] instanceof Authority
) ) {
592 throw new InvalidArgumentException(
593 __METHOD__
. ' called with the `private` option set to something ' .
594 'other than an Authority object'
598 $time = $options['time'] ??
false;
599 # First try to find a matching current version of a file...
600 if ( !$this->fileFactoryKey
) {
601 return false; // find-by-sha1 not supported
603 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
604 if ( $img && $img->exists() ) {
607 # Now try to find a matching old version of a file...
608 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
609 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
610 if ( $img && $img->exists() ) {
611 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
612 return $img; // always OK
614 // If its not empty, its an Authority object
615 !empty( $options['private'] ) &&
616 $img->userCan( File
::DELETED_FILE
, $options['private'] )
627 * Get an array or iterator of file objects for files that have a given
628 * SHA-1 content hash.
631 * @param string $hash SHA-1 hash
634 public function findBySha1( $hash ) {
639 * Get an array of arrays or iterators of file objects for files that
640 * have the given SHA-1 content hashes.
642 * @param string[] $hashes An array of hashes
643 * @return File[][] An Array of arrays or iterators of file objects and the hash as key
645 public function findBySha1s( array $hashes ) {
647 foreach ( $hashes as $hash ) {
648 $files = $this->findBySha1( $hash );
649 if ( count( $files ) ) {
650 $result[$hash] = $files;
658 * Return an array of files where the name starts with $prefix.
661 * @param string $prefix The prefix to search for
662 * @param int $limit The maximum amount of files to return
663 * @return LocalFile[]
665 public function findFilesByPrefix( $prefix, $limit ) {
670 * Get the URL of thumb.php
674 public function getThumbScriptUrl() {
675 return $this->thumbScriptUrl
;
679 * Get the URL thumb.php requests are being proxied to
683 public function getThumbProxyUrl() {
684 return $this->thumbProxyUrl
;
688 * Get the secret key for the proxied thumb service
692 public function getThumbProxySecret() {
693 return $this->thumbProxySecret
;
697 * Returns true if the repository can transform files via a 404 handler
701 public function canTransformVia404() {
702 return $this->transformVia404
;
706 * Returns true if the repository can transform files locally.
711 public function canTransformLocally() {
712 return !$this->disableLocalTransform
;
716 * Get the name of a file from its title
718 * @param PageIdentity|LinkTarget $title
721 public function getNameFromTitle( $title ) {
723 $this->initialCapital
!=
724 MediaWikiServices
::getInstance()->getNamespaceInfo()->isCapitalized( NS_FILE
)
726 $name = $title->getDBkey();
727 if ( $this->initialCapital
) {
728 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
731 $name = $title->getDBkey();
738 * Get the public zone root storage directory of the repository
742 public function getRootDirectory() {
743 return $this->getZonePath( 'public' );
747 * Get a relative path including trailing slash, e.g. f/fa/
748 * If the repo is not hashed, returns an empty string
750 * @param string $name Name of file
753 public function getHashPath( $name ) {
754 return self
::getHashPathForLevel( $name, $this->hashLevels
);
758 * Get a relative path including trailing slash, e.g. f/fa/
759 * If the repo is not hashed, returns an empty string
761 * @param string $suffix Basename of file from FileRepo::storeTemp()
764 public function getTempHashPath( $suffix ) {
765 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
766 $name = $parts[1] ??
$suffix; // hash path is not based on timestamp
767 return self
::getHashPathForLevel( $name, $this->hashLevels
);
771 * @param string $name
775 protected static function getHashPathForLevel( $name, $levels ) {
776 if ( $levels == 0 ) {
779 $hash = md5( $name );
781 for ( $i = 1; $i <= $levels; $i++
) {
782 $path .= substr( $hash, 0, $i ) . '/';
790 * Get the number of hash directory levels
794 public function getHashLevels() {
795 return $this->hashLevels
;
799 * Get the name of this repository, as specified by $info['name]' to the constructor
803 public function getName() {
808 * Make an url to this repo
810 * @param string|array $query Query string to append
811 * @param string $entry Entry point; defaults to index
812 * @return string|false False on failure
814 public function makeUrl( $query = '', $entry = 'index' ) {
815 if ( $this->scriptDirUrl
!== null ) {
816 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}.php", $query );
823 * Get the URL of an image description page. May return false if it is
824 * unknown or not applicable. In general this should only be called by the
825 * File class, since it may return invalid results for certain kinds of
826 * repositories. Use File::getDescriptionUrl() in user code.
828 * In particular, it uses the article paths as specified to the repository
829 * constructor, whereas local repositories use the local Title functions.
831 * @param string $name
832 * @return string|false
834 public function getDescriptionUrl( $name ) {
835 $encName = wfUrlencode( $name );
836 if ( $this->descBaseUrl
!== null ) {
837 # "http://example.com/wiki/File:"
838 return $this->descBaseUrl
. $encName;
840 if ( $this->articleUrl
!== null ) {
841 # "http://example.com/wiki/$1"
842 # We use "Image:" as the canonical namespace for
843 # compatibility across all MediaWiki versions.
844 return str_replace( '$1',
845 "Image:$encName", $this->articleUrl
);
847 if ( $this->scriptDirUrl
!== null ) {
848 # "http://example.com/w"
849 # We use "Image:" as the canonical namespace for
850 # compatibility across all MediaWiki versions,
851 # and just sort of hope index.php is right. ;)
852 return $this->makeUrl( "title=Image:$encName" );
859 * Get the URL of the content-only fragment of the description page. For
860 * MediaWiki this means action=render. This should only be called by the
861 * repository's file class, since it may return invalid results. User code
862 * should use File::getDescriptionText().
864 * @param string $name Name of image to fetch
865 * @param string|null $lang Language to fetch it in, if any.
866 * @return string|false
868 public function getDescriptionRenderUrl( $name, $lang = null ) {
869 $query = 'action=render';
870 if ( $lang !== null ) {
871 $query .= '&uselang=' . urlencode( $lang );
873 if ( $this->scriptDirUrl
!== null ) {
874 return $this->makeUrl(
876 wfUrlencode( 'Image:' . $name ) .
879 $descUrl = $this->getDescriptionUrl( $name );
881 return wfAppendQuery( $descUrl, $query );
889 * Get the URL of the stylesheet to apply to description pages
891 * @return string|false False on failure
893 public function getDescriptionStylesheetUrl() {
894 if ( $this->scriptDirUrl
!== null ) {
895 // Must match canonical query parameter order for optimum caching
896 // See HTMLCacheUpdater::getUrls
897 return $this->makeUrl( 'title=MediaWiki:Filepage.css&action=raw&ctype=text/css' );
904 * Store a file to a given destination.
906 * Using FSFile/TempFSFile can improve performance via caching.
907 * Using TempFSFile can further improve performance by signalling that it is safe
908 * to touch the source file or write extended attribute metadata to it directly.
910 * @param string|FSFile $srcPath Source file system path, storage path, or virtual URL
911 * @param string $dstZone Destination zone
912 * @param string $dstRel Destination relative path
913 * @param int $flags Bitwise combination of the following flags:
914 * self::OVERWRITE Overwrite an existing destination file instead of failing
915 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
916 * same contents as the source
917 * self::SKIP_LOCKING Skip any file locking when doing the store
920 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
921 $this->assertWritableRepo(); // fail out if read-only
923 $status = $this->storeBatch( [ [ $srcPath, $dstZone, $dstRel ] ], $flags );
924 if ( $status->successCount
== 0 ) {
925 $status->setOK( false );
932 * Store a batch of files
934 * @see FileRepo::store()
936 * @param array $triplets (src, dest zone, dest rel) triplets as per store()
937 * @param int $flags Bitwise combination of the following flags:
938 * self::OVERWRITE Overwrite an existing destination file instead of failing
939 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
940 * same contents as the source
941 * self::SKIP_LOCKING Skip any file locking when doing the store
944 public function storeBatch( array $triplets, $flags = 0 ) {
945 $this->assertWritableRepo(); // fail out if read-only
947 if ( $flags & self
::DELETE_SOURCE
) {
948 throw new InvalidArgumentException( "DELETE_SOURCE not supported in " . __METHOD__
);
951 $status = $this->newGood();
952 $backend = $this->backend
; // convenience
955 // Validate each triplet and get the store operation...
956 foreach ( $triplets as [ $src, $dstZone, $dstRel ] ) {
957 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
959 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )"
961 // Resolve source path
962 if ( $src instanceof FSFile
) {
965 $src = $this->resolveToStoragePathIfVirtual( $src );
966 $op = FileBackend
::isStoragePath( $src ) ?
'copy' : 'store';
968 // Resolve destination path
969 $root = $this->getZonePath( $dstZone );
971 throw new RuntimeException( "Invalid zone: $dstZone" );
973 if ( !$this->validateFilename( $dstRel ) ) {
974 throw new RuntimeException( 'Validation error in $dstRel' );
976 $dstPath = "$root/$dstRel";
977 $dstDir = dirname( $dstPath );
978 // Create destination directories for this triplet
979 if ( !$this->initDirectory( $dstDir )->isOK() ) {
980 return $this->newFatal( 'directorycreateerror', $dstDir );
983 // Copy the source file to the destination
986 'src' => $src, // storage path (copy) or local file path (store)
988 'overwrite' => (bool)( $flags & self
::OVERWRITE
),
989 'overwriteSame' => (bool)( $flags & self
::OVERWRITE_SAME
),
993 // Execute the store operation for each triplet
994 $opts = [ 'force' => true ];
995 if ( $flags & self
::SKIP_LOCKING
) {
996 $opts['nonLocking'] = true;
999 return $status->merge( $backend->doOperations( $operations, $opts ) );
1003 * Deletes a batch of files.
1004 * Each file can be a (zone, rel) pair, virtual url, storage path.
1005 * It will try to delete each file, but ignores any errors that may occur.
1007 * @param string[] $files List of files to delete
1008 * @param int $flags Bitwise combination of the following flags:
1009 * self::SKIP_LOCKING Skip any file locking when doing the deletions
1012 public function cleanupBatch( array $files, $flags = 0 ) {
1013 $this->assertWritableRepo(); // fail out if read-only
1015 $status = $this->newGood();
1018 foreach ( $files as $path ) {
1019 if ( is_array( $path ) ) {
1020 // This is a pair, extract it
1021 [ $zone, $rel ] = $path;
1022 $path = $this->getZonePath( $zone ) . "/$rel";
1024 // Resolve source to a storage path if virtual
1025 $path = $this->resolveToStoragePathIfVirtual( $path );
1027 $operations[] = [ 'op' => 'delete', 'src' => $path ];
1029 // Actually delete files from storage...
1030 $opts = [ 'force' => true ];
1031 if ( $flags & self
::SKIP_LOCKING
) {
1032 $opts['nonLocking'] = true;
1035 return $status->merge( $this->backend
->doOperations( $operations, $opts ) );
1039 * Import a file from the local file system into the repo.
1040 * This does no locking and overrides existing files.
1041 * This function can be used to write to otherwise read-only foreign repos.
1042 * This is intended for copying generated thumbnails into the repo.
1044 * Using FSFile/TempFSFile can improve performance via caching.
1045 * Using TempFSFile can further improve performance by signalling that it is safe
1046 * to touch the source file or write extended attribute metadata to it directly.
1048 * @param string|FSFile $src Source file system path, storage path, or virtual URL
1049 * @param string $dst Virtual URL or storage path
1050 * @param array|string|null $options An array consisting of a key named headers
1051 * listing extra headers. If a string, taken as content-disposition header.
1052 * (Support for array of options new in 1.23)
1055 final public function quickImport( $src, $dst, $options = null ) {
1056 return $this->quickImportBatch( [ [ $src, $dst, $options ] ] );
1060 * Import a batch of files from the local file system into the repo.
1061 * This does no locking and overrides existing files.
1062 * This function can be used to write to otherwise read-only foreign repos.
1063 * This is intended for copying generated thumbnails into the repo.
1065 * @see FileRepo::quickImport()
1067 * All path parameters may be a file system path, storage path, or virtual URL.
1068 * When "headers" are given they are used as HTTP headers if supported.
1070 * @param array $triples List of (source path or FSFile, destination path, disposition)
1073 public function quickImportBatch( array $triples ) {
1074 $status = $this->newGood();
1076 foreach ( $triples as $triple ) {
1077 [ $src, $dst ] = $triple;
1078 if ( $src instanceof FSFile
) {
1081 $src = $this->resolveToStoragePathIfVirtual( $src );
1082 $op = FileBackend
::isStoragePath( $src ) ?
'copy' : 'store';
1084 $dst = $this->resolveToStoragePathIfVirtual( $dst );
1086 if ( !isset( $triple[2] ) ) {
1088 } elseif ( is_string( $triple[2] ) ) {
1090 $headers = [ 'Content-Disposition' => $triple[2] ];
1091 } elseif ( is_array( $triple[2] ) && isset( $triple[2]['headers'] ) ) {
1092 $headers = $triple[2]['headers'];
1099 'src' => $src, // storage path (copy) or local path/FSFile (store)
1101 'headers' => $headers
1103 $status->merge( $this->initDirectory( dirname( $dst ) ) );
1106 return $status->merge( $this->backend
->doQuickOperations( $operations ) );
1110 * Purge a file from the repo. This does no locking.
1111 * This function can be used to write to otherwise read-only foreign repos.
1112 * This is intended for purging thumbnails.
1114 * @param string $path Virtual URL or storage path
1117 final public function quickPurge( $path ) {
1118 return $this->quickPurgeBatch( [ $path ] );
1122 * Deletes a directory if empty.
1123 * This function can be used to write to otherwise read-only foreign repos.
1125 * @param string $dir Virtual URL (or storage path) of directory to clean
1128 public function quickCleanDir( $dir ) {
1129 return $this->newGood()->merge(
1130 $this->backend
->clean(
1131 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1137 * Purge a batch of files from the repo.
1138 * This function can be used to write to otherwise read-only foreign repos.
1139 * This does no locking and is intended for purging thumbnails.
1141 * @param string[] $paths List of virtual URLs or storage paths
1144 public function quickPurgeBatch( array $paths ) {
1145 $status = $this->newGood();
1147 foreach ( $paths as $path ) {
1150 'src' => $this->resolveToStoragePathIfVirtual( $path ),
1151 'ignoreMissingSource' => true
1154 $status->merge( $this->backend
->doQuickOperations( $operations ) );
1160 * Pick a random name in the temp zone and store a file to it.
1161 * Returns a Status object with the file Virtual URL in the value,
1162 * file can later be disposed using FileRepo::freeTemp().
1164 * @param string $originalName The base name of the file as specified
1165 * by the user. The file extension will be maintained.
1166 * @param string $srcPath The current location of the file.
1167 * @return Status Object with the URL in the value.
1169 public function storeTemp( $originalName, $srcPath ) {
1170 $this->assertWritableRepo(); // fail out if read-only
1172 $date = MWTimestamp
::getInstance()->format( 'YmdHis' );
1173 $hashPath = $this->getHashPath( $originalName );
1174 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
1175 $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
1177 $result = $this->quickImport( $srcPath, $virtualUrl );
1178 $result->value
= $virtualUrl;
1184 * Remove a temporary file or mark it for garbage collection
1186 * @param string $virtualUrl The virtual URL returned by FileRepo::storeTemp()
1187 * @return bool True on success, false on failure
1189 public function freeTemp( $virtualUrl ) {
1190 $this->assertWritableRepo(); // fail out if read-only
1192 $temp = $this->getVirtualUrl( 'temp' );
1193 if ( !str_starts_with( $virtualUrl, $temp ) ) {
1194 wfDebug( __METHOD__
. ": Invalid temp virtual URL" );
1199 return $this->quickPurge( $virtualUrl )->isOK();
1203 * Concatenate a list of temporary files into a target file location.
1205 * @param string[] $srcPaths Ordered list of source virtual URLs/storage paths
1206 * @param string $dstPath Target file system path
1207 * @param int $flags Bitwise combination of the following flags:
1208 * self::DELETE_SOURCE Delete the source files on success
1211 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
1212 $this->assertWritableRepo(); // fail out if read-only
1214 $status = $this->newGood();
1217 foreach ( $srcPaths as $srcPath ) {
1218 // Resolve source to a storage path if virtual
1219 $source = $this->resolveToStoragePathIfVirtual( $srcPath );
1220 $sources[] = $source; // chunk to merge
1223 // Concatenate the chunks into one FS file
1224 $params = [ 'srcs' => $sources, 'dst' => $dstPath ];
1225 $status->merge( $this->backend
->concatenate( $params ) );
1226 if ( !$status->isOK() ) {
1230 // Delete the sources if required
1231 if ( $flags & self
::DELETE_SOURCE
) {
1232 $status->merge( $this->quickPurgeBatch( $srcPaths ) );
1235 // Make sure status is OK, despite any quickPurgeBatch() fatals
1236 $status->setResult( true );
1242 * Copy or move a file either from a storage path, virtual URL,
1243 * or file system path, into this repository at the specified destination location.
1245 * Returns a Status object. On success, the value contains "new" or
1246 * "archived", to indicate whether the file was new with that name.
1248 * Using FSFile/TempFSFile can improve performance via caching.
1249 * Using TempFSFile can further improve performance by signalling that it is safe
1250 * to touch the source file or write extended attribute metadata to it directly.
1252 * Options to $options include:
1253 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1255 * @param string|FSFile $src The source file system path, storage path, or URL
1256 * @param string $dstRel The destination relative path
1257 * @param string $archiveRel The relative path where the existing file is to
1258 * be archived, if there is one. Relative to the public zone root.
1259 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1260 * that the source file should be deleted if possible
1261 * @param array $options Optional additional parameters
1264 public function publish(
1265 $src, $dstRel, $archiveRel, $flags = 0, array $options = []
1267 $this->assertWritableRepo(); // fail out if read-only
1269 $status = $this->publishBatch(
1270 [ [ $src, $dstRel, $archiveRel, $options ] ], $flags );
1271 if ( $status->successCount
== 0 ) {
1272 $status->setOK( false );
1274 $status->value
= $status->value
[0] ??
false;
1280 * Publish a batch of files
1282 * @see FileRepo::publish()
1284 * @param array $ntuples (source, dest, archive) triplets or
1285 * (source, dest, archive, options) 4-tuples as per publish().
1286 * @param int $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
1287 * that the source files should be deleted if possible
1290 public function publishBatch( array $ntuples, $flags = 0 ) {
1291 $this->assertWritableRepo(); // fail out if read-only
1293 $backend = $this->backend
; // convenience
1294 // Try creating directories
1295 $this->initZones( 'public' );
1297 $status = $this->newGood( [] );
1300 $sourceFSFilesToDelete = []; // cleanup for disk source files
1301 // Validate each triplet and get the store operation...
1302 foreach ( $ntuples as $ntuple ) {
1303 [ $src, $dstRel, $archiveRel ] = $ntuple;
1304 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1306 $options = $ntuple[3] ??
[];
1307 // Resolve source to a storage path if virtual
1308 $srcPath = $this->resolveToStoragePathIfVirtual( $srcPath );
1309 if ( !$this->validateFilename( $dstRel ) ) {
1310 throw new RuntimeException( 'Validation error in $dstRel' );
1312 if ( !$this->validateFilename( $archiveRel ) ) {
1313 throw new RuntimeException( 'Validation error in $archiveRel' );
1316 $publicRoot = $this->getZonePath( 'public' );
1317 $dstPath = "$publicRoot/$dstRel";
1318 $archivePath = "$publicRoot/$archiveRel";
1320 $dstDir = dirname( $dstPath );
1321 $archiveDir = dirname( $archivePath );
1322 // Abort immediately on directory creation errors since they're likely to be repetitive
1323 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1324 return $this->newFatal( 'directorycreateerror', $dstDir );
1326 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1327 return $this->newFatal( 'directorycreateerror', $archiveDir );
1330 // Set any desired headers to be use in GET/HEAD responses
1331 $headers = $options['headers'] ??
[];
1333 // Archive destination file if it exists.
1334 // This will check if the archive file also exists and fail if does.
1335 // This is a check to avoid data loss. On Windows and Linux,
1336 // copy() will overwrite, so the existence check is vulnerable to
1337 // race conditions unless a functioning LockManager is used.
1338 // LocalFile also uses SELECT FOR UPDATE for synchronization.
1342 'dst' => $archivePath,
1343 'ignoreMissingSource' => true
1346 // Copy (or move) the source file to the destination
1347 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1349 'op' => ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy',
1352 'overwrite' => true, // replace current
1353 'headers' => $headers
1358 'src' => $src, // storage path (copy) or local path/FSFile (store)
1360 'overwrite' => true, // replace current
1361 'headers' => $headers
1363 if ( $flags & self
::DELETE_SOURCE
) {
1364 $sourceFSFilesToDelete[] = $srcPath;
1369 // Execute the operations for each triplet
1370 $status->merge( $backend->doOperations( $operations ) );
1371 // Find out which files were archived...
1372 foreach ( $ntuples as $i => $ntuple ) {
1373 [ , , $archiveRel ] = $ntuple;
1374 $archivePath = $this->getZonePath( 'public' ) . "/$archiveRel";
1375 if ( $this->fileExists( $archivePath ) ) {
1376 $status->value
[$i] = 'archived';
1378 $status->value
[$i] = 'new';
1381 // Cleanup for disk source files...
1382 foreach ( $sourceFSFilesToDelete as $file ) {
1383 AtEase
::suppressWarnings();
1384 unlink( $file ); // FS cleanup
1385 AtEase
::restoreWarnings();
1392 * Creates a directory with the appropriate zone permissions.
1393 * Callers are responsible for doing read-only and "writable repo" checks.
1395 * @param string $dir Virtual URL (or storage path) of directory to clean
1396 * @return Status Good status without value for success, fatal otherwise.
1398 protected function initDirectory( $dir ) {
1399 $path = $this->resolveToStoragePathIfVirtual( $dir );
1400 [ , $container, ] = FileBackend
::splitStoragePath( $path );
1402 $params = [ 'dir' => $path ];
1403 if ( $this->isPrivate
1404 ||
$container === $this->zones
['deleted']['container']
1405 ||
$container === $this->zones
['temp']['container']
1407 # Take all available measures to prevent web accessibility of new deleted
1408 # directories, in case the user has not configured offline storage
1409 $params = [ 'noAccess' => true, 'noListing' => true ] +
$params;
1412 return $this->newGood()->merge( $this->backend
->prepare( $params ) );
1416 * Deletes a directory if empty.
1418 * @param string $dir Virtual URL (or storage path) of directory to clean
1421 public function cleanDir( $dir ) {
1422 $this->assertWritableRepo(); // fail out if read-only
1424 return $this->newGood()->merge(
1425 $this->backend
->clean(
1426 [ 'dir' => $this->resolveToStoragePathIfVirtual( $dir ) ]
1432 * Checks existence of a file
1434 * @param string $file Virtual URL (or storage path) of file to check
1435 * @return bool|null Whether the file exists, or null in case of I/O errors
1437 public function fileExists( $file ) {
1438 $result = $this->fileExistsBatch( [ $file ] );
1444 * Checks existence of an array of files.
1446 * @param string[] $files Virtual URLs (or storage paths) of files to check
1447 * @return array<string|int,bool|null> Map of files and either bool indicating whether the files exist,
1448 * or null in case of I/O errors
1450 public function fileExistsBatch( array $files ) {
1451 $paths = array_map( [ $this, 'resolveToStoragePathIfVirtual' ], $files );
1452 $this->backend
->preloadFileStat( [ 'srcs' => $paths ] );
1455 foreach ( $paths as $key => $path ) {
1456 $result[$key] = $this->backend
->fileExists( [ 'src' => $path ] );
1463 * Move a file to the deletion archive.
1464 * If no valid deletion archive exists, this may either delete the file
1465 * or throw an exception, depending on the preference of the repository
1467 * @param mixed $srcRel Relative path for the file to be deleted
1468 * @param mixed $archiveRel Relative path for the archive location.
1469 * Relative to a private archive directory.
1472 public function delete( $srcRel, $archiveRel ) {
1473 $this->assertWritableRepo(); // fail out if read-only
1475 return $this->deleteBatch( [ [ $srcRel, $archiveRel ] ] );
1479 * Move a group of files to the deletion archive.
1481 * If no valid deletion archive is configured, this may either delete the
1482 * file or throw an exception, depending on the preference of the repository.
1484 * The overwrite policy is determined by the repository -- currently LocalRepo
1485 * assumes a naming scheme in the deleted zone based on content hash, as
1486 * opposed to the public zone which is assumed to be unique.
1488 * @param array $sourceDestPairs Array of source/destination pairs. Each element
1489 * is a two-element array containing the source file path relative to the
1490 * public root in the first element, and the archive file path relative
1491 * to the deleted zone root in the second element.
1494 public function deleteBatch( array $sourceDestPairs ) {
1495 $this->assertWritableRepo(); // fail out if read-only
1497 // Try creating directories
1498 $this->initZones( [ 'public', 'deleted' ] );
1500 $status = $this->newGood();
1502 $backend = $this->backend
; // convenience
1504 // Validate filenames and create archive directories
1505 foreach ( $sourceDestPairs as [ $srcRel, $archiveRel ] ) {
1506 if ( !$this->validateFilename( $srcRel ) ) {
1507 throw new RuntimeException( __METHOD__
. ':Validation error in $srcRel' );
1508 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1509 throw new RuntimeException( __METHOD__
. ':Validation error in $archiveRel' );
1512 $publicRoot = $this->getZonePath( 'public' );
1513 $srcPath = "{$publicRoot}/$srcRel";
1515 $deletedRoot = $this->getZonePath( 'deleted' );
1516 $archivePath = "{$deletedRoot}/{$archiveRel}";
1517 $archiveDir = dirname( $archivePath ); // does not touch FS
1519 // Create destination directories
1520 if ( !$this->initDirectory( $archiveDir )->isGood() ) {
1521 return $this->newFatal( 'directorycreateerror', $archiveDir );
1527 'dst' => $archivePath,
1528 // We may have 2+ identical files being deleted,
1529 // all of which will map to the same destination file
1530 'overwriteSame' => true // also see T33792
1534 // Move the files by execute the operations for each pair.
1535 // We're now committed to returning an OK result, which will
1536 // lead to the files being moved in the DB also.
1537 $opts = [ 'force' => true ];
1538 return $status->merge( $backend->doOperations( $operations, $opts ) );
1542 * Delete files in the deleted directory if they are not referenced in the filearchive table
1545 * @param string[] $storageKeys
1547 public function cleanupDeletedBatch( array $storageKeys ) {
1548 $this->assertWritableRepo();
1552 * Get a relative path for a deletion archive key,
1553 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1555 * @param string $key
1558 public function getDeletedHashPath( $key ) {
1559 if ( strlen( $key ) < 31 ) {
1560 throw new InvalidArgumentException( "Invalid storage key '$key'." );
1563 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1564 $path .= $key[$i] . '/';
1571 * If a path is a virtual URL, resolve it to a storage path.
1572 * Otherwise, just return the path as it is.
1574 * @param string $path
1577 protected function resolveToStoragePathIfVirtual( $path ) {
1578 if ( self
::isVirtualUrl( $path ) ) {
1579 return $this->resolveVirtualUrl( $path );
1586 * Get a local FS copy of a file with a given virtual URL/storage path.
1587 * Temporary files may be purged when the file object falls out of scope.
1589 * @param string $virtualUrl
1590 * @return TempFSFile|null|false Returns false for missing file, null on failure
1592 public function getLocalCopy( $virtualUrl ) {
1593 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1595 return $this->backend
->getLocalCopy( [ 'src' => $path ] );
1599 * Get a local FS file with a given virtual URL/storage path.
1600 * The file is either an original or a copy. It should not be changed.
1601 * Temporary files may be purged when the file object falls out of scope.
1603 * @param string $virtualUrl
1604 * @return FSFile|null|false Returns false for missing file, null on failure.
1606 public function getLocalReference( $virtualUrl ) {
1607 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1609 return $this->backend
->getLocalReference( [ 'src' => $path ] );
1613 * Add a file to a Shellbox command as an input file
1615 * @param BoxedCommand $command
1616 * @param string $boxedName
1617 * @param string $virtualUrl
1618 * @return StatusValue
1621 public function addShellboxInputFile( BoxedCommand
$command, string $boxedName,
1624 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1626 return $this->backend
->addShellboxInputFile( $command, $boxedName, [ 'src' => $path ] );
1630 * Get properties of a file with a given virtual URL/storage path.
1631 * Properties should ultimately be obtained via FSFile::getProps().
1633 * @param string $virtualUrl
1636 public function getFileProps( $virtualUrl ) {
1637 $fsFile = $this->getLocalReference( $virtualUrl );
1638 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1640 $props = $mwProps->getPropsFromPath( $fsFile->getPath(), true );
1642 $props = $mwProps->newPlaceholderProps();
1649 * Get the timestamp of a file with a given virtual URL/storage path
1651 * @param string $virtualUrl
1652 * @return string|false False on failure
1654 public function getFileTimestamp( $virtualUrl ) {
1655 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1657 return $this->backend
->getFileTimestamp( [ 'src' => $path ] );
1661 * Get the size of a file with a given virtual URL/storage path
1663 * @param string $virtualUrl
1666 public function getFileSize( $virtualUrl ) {
1667 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1669 return $this->backend
->getFileSize( [ 'src' => $path ] );
1673 * Get the sha1 (base 36) of a file with a given virtual URL/storage path
1675 * @param string $virtualUrl
1676 * @return string|false
1678 public function getFileSha1( $virtualUrl ) {
1679 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1681 return $this->backend
->getFileSha1Base36( [ 'src' => $path ] );
1685 * Attempt to stream a file with the given virtual URL/storage path
1687 * @param string $virtualUrl
1688 * @param array $headers Additional HTTP headers to send on success
1689 * @param array $optHeaders HTTP request headers (if-modified-since, range, ...)
1693 public function streamFileWithStatus( $virtualUrl, $headers = [], $optHeaders = [] ) {
1694 $path = $this->resolveToStoragePathIfVirtual( $virtualUrl );
1695 $params = [ 'src' => $path, 'headers' => $headers, 'options' => $optHeaders ];
1697 // T172851: HHVM does not flush the output properly, causing OOM
1698 ob_start( null, 1_048_576
);
1699 ob_implicit_flush( true );
1701 $status = $this->newGood()->merge( $this->backend
->streamFile( $params ) );
1703 // T186565: Close the buffer, unless it has already been closed
1704 // in HTTPFileStreamer::resetOutputBuffers().
1705 if ( ob_get_status() ) {
1713 * Call a callback function for every public regular file in the repository.
1714 * This only acts on the current version of files, not any old versions.
1715 * May use either the database or the filesystem.
1717 * @param callable $callback
1720 public function enumFiles( $callback ) {
1721 $this->enumFilesInStorage( $callback );
1725 * Call a callback function for every public file in the repository.
1726 * May use either the database or the filesystem.
1728 * @param callable $callback
1731 protected function enumFilesInStorage( $callback ) {
1732 $publicRoot = $this->getZonePath( 'public' );
1733 $numDirs = 1 << ( $this->hashLevels
* 4 );
1734 // Use a priori assumptions about directory structure
1735 // to reduce the tree height of the scanning process.
1736 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1737 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1738 $path = $publicRoot;
1739 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1740 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1742 $iterator = $this->backend
->getFileList( [ 'dir' => $path ] );
1743 if ( $iterator === null ) {
1744 throw new RuntimeException( __METHOD__
. ': could not get file listing for ' . $path );
1746 foreach ( $iterator as $name ) {
1747 // Each item returned is a public file
1748 call_user_func( $callback, "{$path}/{$name}" );
1754 * Determine if a relative path is valid, i.e. not blank or involving directory traversal
1756 * @param string $filename
1759 public function validateFilename( $filename ) {
1760 if ( strval( $filename ) == '' ) {
1764 return FileBackend
::isPathTraversalFree( $filename );
1768 * Get a callback function to use for cleaning error message parameters
1772 private function getErrorCleanupFunction() {
1773 switch ( $this->pathDisclosureProtection
) {
1775 case 'simple': // b/c
1776 $callback = [ $this, 'passThrough' ];
1778 default: // 'paranoid'
1779 $callback = [ $this, 'paranoidClean' ];
1785 * Path disclosure protection function
1787 * @param string $param
1790 public function paranoidClean( $param ) {
1795 * Path disclosure protection function
1797 * @param string $param
1800 public function passThrough( $param ) {
1805 * Create a new fatal error
1807 * @param string $message
1808 * @param mixed ...$parameters
1811 public function newFatal( $message, ...$parameters ) {
1812 $status = Status
::newFatal( $message, ...$parameters );
1813 $status->cleanCallback
= $this->getErrorCleanupFunction();
1819 * Create a new good result
1821 * @param null|mixed $value
1824 public function newGood( $value = null ) {
1825 $status = Status
::newGood( $value );
1826 $status->cleanCallback
= $this->getErrorCleanupFunction();
1832 * Checks if there is a redirect named as $title. If there is, return the
1833 * title object. If not, return false.
1836 * @param PageIdentity|LinkTarget $title Title of image
1837 * @return Title|false
1839 public function checkRedirect( $title ) {
1844 * Invalidates image redirect cache related to that image
1845 * Doesn't do anything for repositories that don't support image redirects.
1848 * @param PageIdentity|LinkTarget $title Title of image
1850 public function invalidateImageRedirect( $title ) {
1854 * Get the human-readable name of the repo
1858 public function getDisplayName() {
1859 $sitename = MediaWikiServices
::getInstance()->getMainConfig()->get( MainConfigNames
::Sitename
);
1861 if ( $this->isLocal() ) {
1865 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1866 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1870 * Get the portion of the file that contains the origin file name.
1871 * If that name is too long, then the name "thumbnail.<ext>" will be given.
1873 * @param string $name
1876 public function nameForThumb( $name ) {
1877 if ( strlen( $name ) > $this->abbrvThreshold
) {
1878 $ext = FileBackend
::extensionFromPath( $name );
1879 $name = ( $ext == '' ) ?
'thumbnail' : "thumbnail.$ext";
1886 * Returns true if this the local file repository.
1890 public function isLocal() {
1891 return $this->getName() == 'local';
1895 * Get a global, repository-qualified, WAN cache key
1897 * This might be called from either the site context of the wiki that owns the repo or
1898 * the site context of another wiki that simply has access to the repo. This returns
1899 * false if the repository's cache is not accessible from the current site context.
1901 * @param string $kClassSuffix Key collection name suffix (added to this repo class)
1902 * @param mixed ...$components Additional key components
1903 * @return string|false
1905 public function getSharedCacheKey( $kClassSuffix, ...$components ) {
1910 * Get a site-local, repository-qualified, WAN cache key
1912 * These cache keys are not shared among different site context and thus cannot be
1913 * directly invalidated when repo objects are modified. These are useful when there
1914 * is no accessible global cache or the values depend on the current site context.
1916 * @param string $kClassSuffix Key collection name suffix (added to this repo class)
1917 * @param mixed ...$components Additional key components
1920 public function getLocalCacheKey( $kClassSuffix, ...$components ) {
1921 return $this->wanCache
->makeKey(
1922 'filerepo-' . $kClassSuffix,
1929 * Get a temporary private FileRepo associated with this repo.
1931 * Files will be created in the temp zone of this repo.
1932 * It will have the same backend as this repo.
1934 * @return TempFileRepo
1936 public function getTempRepo() {
1937 return new TempFileRepo( [
1938 'name' => "{$this->name}-temp",
1939 'backend' => $this->backend
,
1942 // Same place storeTemp() uses in the base repo, though
1943 // the path hashing is mismatched, which is annoying.
1944 'container' => $this->zones
['temp']['container'],
1945 'directory' => $this->zones
['temp']['directory']
1948 'container' => $this->zones
['temp']['container'],
1949 'directory' => $this->zones
['temp']['directory'] == ''
1951 : $this->zones
['temp']['directory'] . '/thumb'
1954 'container' => $this->zones
['temp']['container'],
1955 'directory' => $this->zones
['temp']['directory'] == ''
1957 : $this->zones
['temp']['directory'] . '/transcoded'
1960 'hashLevels' => $this->hashLevels
, // performance
1961 'isPrivate' => true // all in temp zone
1966 * Get an UploadStash associated with this repo.
1968 * @param UserIdentity|null $user
1969 * @return UploadStash
1971 public function getUploadStash( ?UserIdentity
$user = null ) {
1972 return new UploadStash( $this, $user );
1976 * Throw an exception if this repo is read-only by design.
1977 * This does not and should not check getReadOnlyReason().
1979 * @throws LogicException
1981 protected function assertWritableRepo() {
1985 * Return information about the repository.
1990 public function getInfo() {
1992 'name' => $this->getName(),
1993 'displayname' => $this->getDisplayName(),
1994 'rootUrl' => $this->getZoneUrl( 'public' ),
1995 'local' => $this->isLocal(),
1998 $optionalSettings = [
2006 'descriptionCacheExpiry',
2008 foreach ( $optionalSettings as $k ) {
2009 if ( $this->$k !== null ) {
2010 $ret[$k] = $this->$k;
2013 if ( $this->favicon
!== null ) {
2014 // Expand any local path to full URL to improve API usability (T77093).
2015 $ret['favicon'] = MediaWikiServices
::getInstance()->getUrlUtils()
2016 ->expand( $this->favicon
);
2023 * Returns whether or not storage is SHA-1 based
2026 public function hasSha1Storage() {
2027 return $this->hasSha1Storage
;
2031 * Returns whether or not repo supports having originals SHA-1s in the thumb URLs
2034 public function supportsSha1URLs() {
2035 return $this->supportsSha1URLs
;