summaryrefslogtreecommitdiff
path: root/includes/filerepo
diff options
context:
space:
mode:
Diffstat (limited to 'includes/filerepo')
-rw-r--r--includes/filerepo/FSRepo.php20
-rw-r--r--includes/filerepo/FileRepo.php659
-rw-r--r--includes/filerepo/FileRepoStatus.php17
-rw-r--r--includes/filerepo/ForeignAPIRepo.php138
-rw-r--r--includes/filerepo/ForeignDBRepo.php40
-rw-r--r--includes/filerepo/ForeignDBViaLBRepo.php37
-rw-r--r--includes/filerepo/LocalRepo.php66
-rw-r--r--includes/filerepo/NullRepo.php54
-rw-r--r--includes/filerepo/RepoGroup.php120
-rw-r--r--includes/filerepo/backend/FSFile.php233
-rw-r--r--includes/filerepo/backend/FSFileBackend.php600
-rw-r--r--includes/filerepo/backend/FileBackend.php1739
-rw-r--r--includes/filerepo/backend/FileBackendGroup.php156
-rw-r--r--includes/filerepo/backend/FileBackendMultiWrite.php420
-rw-r--r--includes/filerepo/backend/FileOp.php697
-rw-r--r--includes/filerepo/backend/SwiftFileBackend.php877
-rw-r--r--includes/filerepo/backend/TempFSFile.php92
-rw-r--r--includes/filerepo/backend/lockmanager/DBLockManager.php469
-rw-r--r--includes/filerepo/backend/lockmanager/FSLockManager.php202
-rw-r--r--includes/filerepo/backend/lockmanager/LSLockManager.php295
-rw-r--r--includes/filerepo/backend/lockmanager/LockManager.php182
-rw-r--r--includes/filerepo/backend/lockmanager/LockManagerGroup.php89
-rw-r--r--includes/filerepo/file/ArchivedFile.php21
-rw-r--r--includes/filerepo/file/File.php219
-rw-r--r--includes/filerepo/file/ForeignAPIFile.php90
-rw-r--r--includes/filerepo/file/ForeignDBFile.php46
-rw-r--r--includes/filerepo/file/LocalFile.php491
-rw-r--r--includes/filerepo/file/OldLocalFile.php103
-rw-r--r--includes/filerepo/file/UnregisteredLocalFile.php57
29 files changed, 1592 insertions, 6637 deletions
diff --git a/includes/filerepo/FSRepo.php b/includes/filerepo/FSRepo.php
index 22dbdefc..9c8d85dc 100644
--- a/includes/filerepo/FSRepo.php
+++ b/includes/filerepo/FSRepo.php
@@ -2,6 +2,21 @@
/**
* A repository for files accessible via the local filesystem.
*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
* @file
* @ingroup FileRepo
*/
@@ -16,6 +31,11 @@
* @deprecated since 1.19
*/
class FSRepo extends FileRepo {
+
+ /**
+ * @param $info array
+ * @throws MWException
+ */
function __construct( array $info ) {
if ( !isset( $info['backend'] ) ) {
// B/C settings...
diff --git a/includes/filerepo/FileRepo.php b/includes/filerepo/FileRepo.php
index 8d4f2bd9..a31b148a 100644
--- a/includes/filerepo/FileRepo.php
+++ b/includes/filerepo/FileRepo.php
@@ -10,6 +10,21 @@
/**
* Base code for file repositories.
*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
* @file
* @ingroup FileRepo
*/
@@ -20,8 +35,6 @@
* @ingroup FileRepo
*/
class FileRepo {
- const FILES_ONLY = 1;
-
const DELETE_SOURCE = 1;
const OVERWRITE = 2;
const OVERWRITE_SAME = 4;
@@ -38,6 +51,7 @@ class FileRepo {
var $pathDisclosureProtection = 'simple'; // 'paranoid'
var $descriptionCacheExpiry, $url, $thumbUrl;
var $hashLevels, $deletedHashLevels;
+ protected $abbrvThreshold;
/**
* Factory functions for creating new files
@@ -47,7 +61,11 @@ class FileRepo {
var $oldFileFactory = false;
var $fileFactoryKey = false, $oldFileFactoryKey = false;
- function __construct( Array $info = null ) {
+ /**
+ * @param $info array|null
+ * @throws MWException
+ */
+ public function __construct( array $info = null ) {
// Verify required settings presence
if(
$info === null
@@ -96,22 +114,24 @@ class FileRepo {
? $info['deletedHashLevels']
: $this->hashLevels;
$this->transformVia404 = !empty( $info['transformVia404'] );
- $this->zones = isset( $info['zones'] )
- ? $info['zones']
- : array();
+ $this->abbrvThreshold = isset( $info['abbrvThreshold'] )
+ ? $info['abbrvThreshold']
+ : 255;
+ $this->isPrivate = !empty( $info['isPrivate'] );
// Give defaults for the basic zones...
+ $this->zones = isset( $info['zones'] ) ? $info['zones'] : array();
foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
- if ( !isset( $this->zones[$zone] ) ) {
- $this->zones[$zone] = array(
- 'container' => "{$this->name}-{$zone}",
- 'directory' => '' // container root
- );
+ if ( !isset( $this->zones[$zone]['container'] ) ) {
+ $this->zones[$zone]['container'] = "{$this->name}-{$zone}";
+ }
+ if ( !isset( $this->zones[$zone]['directory'] ) ) {
+ $this->zones[$zone]['directory'] = '';
}
}
}
/**
- * Get the file backend instance
+ * Get the file backend instance. Use this function wisely.
*
* @return FileBackend
*/
@@ -120,10 +140,20 @@ class FileRepo {
}
/**
- * Prepare a single zone or list of zones for usage.
- * See initDeletedDir() for additional setup needed for the 'deleted' zone.
- *
+ * Get an explanatory message if this repo is read-only.
+ * This checks if an administrator disabled writes to the backend.
+ *
+ * @return string|bool Returns false if the repo is not read-only
+ */
+ public function getReadOnlyReason() {
+ return $this->backend->getReadOnlyReason();
+ }
+
+ /**
+ * Check if a single zone or list of zones is defined for usage
+ *
* @param $doZones Array Only do a particular zones
+ * @throws MWException
* @return Status
*/
protected function initZones( $doZones = array() ) {
@@ -138,18 +168,6 @@ class FileRepo {
}
/**
- * Take all available measures to prevent web accessibility of new deleted
- * directories, in case the user has not configured offline storage
- *
- * @param $dir string
- * @return void
- */
- protected function initDeletedDir( $dir ) {
- $this->backend->secure( // prevent web access & dir listings
- array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
- }
-
- /**
* Determine if a string is an mwrepo:// URL
*
* @param $url string
@@ -164,7 +182,7 @@ class FileRepo {
* The suffix, if supplied, is considered to be unencoded, and will be
* URL-encoded before being returned.
*
- * @param $suffix string
+ * @param $suffix string|bool
* @return string
*/
public function getVirtualUrl( $suffix = false ) {
@@ -182,6 +200,11 @@ class FileRepo {
* @return String or false
*/
public function getZoneUrl( $zone ) {
+ if ( isset( $this->zones[$zone]['url'] )
+ && in_array( $zone, array( 'public', 'temp', 'thumb' ) ) )
+ {
+ return $this->zones[$zone]['url']; // custom URL
+ }
switch ( $zone ) {
case 'public':
return $this->url;
@@ -197,12 +220,36 @@ class FileRepo {
}
/**
- * Get the backend storage path corresponding to a virtual URL
+ * Get the thumb zone URL configured to be handled by scripts like thumb_handler.php.
+ * This is probably only useful for internal requests, such as from a fast frontend server
+ * to a slower backend server.
+ *
+ * Large sites may use a different host name for uploads than for wikis. In any case, the
+ * wiki configuration is needed in order to use thumb.php. To avoid extracting the wiki ID
+ * from the URL path, one can configure thumb_handler.php to recognize a special path on the
+ * same host name as the wiki that is used for viewing thumbnails.
+ *
+ * @param $zone String: one of: public, deleted, temp, thumb
+ * @return String or false
+ */
+ public function getZoneHandlerUrl( $zone ) {
+ if ( isset( $this->zones[$zone]['handlerUrl'] )
+ && in_array( $zone, array( 'public', 'temp', 'thumb' ) ) )
+ {
+ return $this->zones[$zone]['handlerUrl'];
+ }
+ return false;
+ }
+
+ /**
+ * Get the backend storage path corresponding to a virtual URL.
+ * Use this function wisely.
*
* @param $url string
+ * @throws MWException
* @return string
*/
- function resolveVirtualUrl( $url ) {
+ public function resolveVirtualUrl( $url ) {
if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
throw new MWException( __METHOD__.': unknown protocol' );
}
@@ -223,7 +270,7 @@ class FileRepo {
/**
* The the storage container and base path of a zone
- *
+ *
* @param $zone string
* @return Array (container, base path) or (null, null)
*/
@@ -238,7 +285,7 @@ class FileRepo {
* Get the storage path corresponding to one of the zones
*
* @param $zone string
- * @return string|null
+ * @return string|null Returns null if the zone is not defined
*/
public function getZonePath( $zone ) {
list( $container, $base ) = $this->getZoneLocation( $zone );
@@ -286,16 +333,16 @@ class FileRepo {
*
* @param $title Mixed: Title object or string
* @param $options array Associative array of options:
- * time: requested time for an archived image, or false for the
+ * time: requested time for a specific file version, or false for the
* current version. An image object will be returned which was
- * created at the specified time.
+ * created at the specified time (which may be archived or current).
*
* ignoreRedirect: If true, do not follow file redirects
*
* private: If true, return restricted (deleted) files if the current
* user is allowed to view them. Otherwise, such files will not
* be found.
- * @return File|false
+ * @return File|bool False on failure
*/
public function findFile( $title, $options = array() ) {
$title = File::normalizeTitle( $title );
@@ -344,7 +391,7 @@ class FileRepo {
/**
* Find many files at once.
*
- * @param $items An array of titles, or an array of findFile() options with
+ * @param $items array An array of titles, or an array of findFile() options with
* the "title" option giving the title. Example:
*
* $findItem = array( 'title' => $title, 'private' => true );
@@ -352,7 +399,7 @@ class FileRepo {
* $repo->findFiles( $findBatch );
* @return array
*/
- public function findFiles( $items ) {
+ public function findFiles( array $items ) {
$result = array();
foreach ( $items as $item ) {
if ( is_array( $item ) ) {
@@ -377,12 +424,11 @@ class FileRepo {
* version control should return false if the time is specified.
*
* @param $sha1 String base 36 SHA-1 hash
- * @param $options Option array, same as findFile().
- * @return File|false
+ * @param $options array Option array, same as findFile().
+ * @return File|bool False on failure
*/
public function findFileFromKey( $sha1, $options = array() ) {
$time = isset( $options['time'] ) ? $options['time'] : false;
-
# First try to find a matching current version of a file...
if ( $this->fileFactoryKey ) {
$img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
@@ -411,27 +457,39 @@ class FileRepo {
* SHA-1 content hash.
*
* STUB
+ * @param $hash
+ * @return array
*/
public function findBySha1( $hash ) {
return array();
}
/**
- * Get the public root URL of the repository
+ * Get an array of arrays or iterators of file objects for files that
+ * have the given SHA-1 content hashes.
*
- * @return string|false
+ * @param $hashes array An array of hashes
+ * @return array An Array of arrays or iterators of file objects and the hash as key
*/
- public function getRootUrl() {
- return $this->url;
+ public function findBySha1s( array $hashes ) {
+ $result = array();
+ foreach ( $hashes as $hash ) {
+ $files = $this->findBySha1( $hash );
+ if ( count( $files ) ) {
+ $result[$hash] = $files;
+ }
+ }
+ return $result;
}
/**
- * Returns true if the repository uses a multi-level directory structure
+ * Get the public root URL of the repository
*
+ * @deprecated since 1.20
* @return string
*/
- public function isHashed() {
- return (bool)$this->hashLevels;
+ public function getRootUrl() {
+ return $this->getZoneUrl( 'public' );
}
/**
@@ -456,6 +514,7 @@ class FileRepo {
* Get the name of an image from its title object
*
* @param $title Title
+ * @return String
*/
public function getNameFromTitle( Title $title ) {
global $wgContLang;
@@ -483,7 +542,7 @@ class FileRepo {
* Get a relative path including trailing slash, e.g. f/fa/
* If the repo is not hashed, returns an empty string
*
- * @param $name string
+ * @param $name string Name of file
* @return string
*/
public function getHashPath( $name ) {
@@ -491,11 +550,24 @@ class FileRepo {
}
/**
+ * Get a relative path including trailing slash, e.g. f/fa/
+ * If the repo is not hashed, returns an empty string
+ *
+ * @param $suffix string Basename of file from FileRepo::storeTemp()
+ * @return string
+ */
+ public function getTempHashPath( $suffix ) {
+ $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
+ $name = isset( $parts[1] ) ? $parts[1] : $suffix; // hash path is not based on timestamp
+ return self::getHashPathForLevel( $name, $this->hashLevels );
+ }
+
+ /**
* @param $name
* @param $levels
* @return string
*/
- static function getHashPathForLevel( $name, $levels ) {
+ protected static function getHashPathForLevel( $name, $levels ) {
if ( $levels == 0 ) {
return '';
} else {
@@ -531,7 +603,7 @@ class FileRepo {
*
* @param $query mixed Query string to append
* @param $entry string Entry point; defaults to index
- * @return string|false
+ * @return string|bool False on failure
*/
public function makeUrl( $query = '', $entry = 'index' ) {
if ( isset( $this->scriptDirUrl ) ) {
@@ -611,7 +683,7 @@ class FileRepo {
/**
* Get the URL of the stylesheet to apply to description pages
*
- * @return string|false
+ * @return string|bool False on failure
*/
public function getDescriptionStylesheetUrl() {
if ( isset( $this->scriptDirUrl ) ) {
@@ -624,7 +696,7 @@ class FileRepo {
/**
* Store a file to a given destination.
*
- * @param $srcPath String: source FS path, storage path, or virtual URL
+ * @param $srcPath String: source file system path, storage path, or virtual URL
* @param $dstZone String: destination zone
* @param $dstRel String: destination relative path
* @param $flags Integer: bitwise combination of the following flags:
@@ -636,10 +708,13 @@ class FileRepo {
* @return FileRepoStatus
*/
public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
+ $this->assertWritableRepo(); // fail out if read-only
+
$status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
if ( $status->successCount == 0 ) {
$status->ok = false;
}
+
return $status;
}
@@ -653,12 +728,14 @@ class FileRepo {
* self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
* same contents as the source
* self::SKIP_LOCKING Skip any file locking when doing the store
+ * @throws MWException
* @return FileRepoStatus
*/
- public function storeBatch( $triplets, $flags = 0 ) {
- $backend = $this->backend; // convenience
+ public function storeBatch( array $triplets, $flags = 0 ) {
+ $this->assertWritableRepo(); // fail out if read-only
$status = $this->newGood();
+ $backend = $this->backend; // convenience
$operations = array();
$sourceFSFilesToDelete = array(); // cleanup for disk source files
@@ -680,18 +757,12 @@ class FileRepo {
$dstPath = "$root/$dstRel";
$dstDir = dirname( $dstPath );
// Create destination directories for this triplet
- if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
+ if ( !$this->initDirectory( $dstDir )->isOK() ) {
return $this->newFatal( 'directorycreateerror', $dstDir );
}
- if ( $dstZone == 'deleted' ) {
- $this->initDeletedDir( $dstDir );
- }
-
// Resolve source to a storage path if virtual
- if ( self::isVirtualUrl( $srcPath ) ) {
- $srcPath = $this->resolveVirtualUrl( $srcPath );
- }
+ $srcPath = $this->resolveToStoragePath( $srcPath );
// Get the appropriate file operation
if ( FileBackend::isStoragePath( $srcPath ) ) {
@@ -729,54 +800,136 @@ class FileRepo {
/**
* Deletes a batch of files.
- * Each file can be a (zone, rel) pair, virtual url, storage path, or FS path.
+ * Each file can be a (zone, rel) pair, virtual url, storage path.
* It will try to delete each file, but ignores any errors that may occur.
*
- * @param $pairs array List of files to delete
+ * @param $files array List of files to delete
* @param $flags Integer: bitwise combination of the following flags:
* self::SKIP_LOCKING Skip any file locking when doing the deletions
- * @return void
+ * @return FileRepoStatus
*/
- public function cleanupBatch( $files, $flags = 0 ) {
+ public function cleanupBatch( array $files, $flags = 0 ) {
+ $this->assertWritableRepo(); // fail out if read-only
+
+ $status = $this->newGood();
+
$operations = array();
- $sourceFSFilesToDelete = array(); // cleanup for disk source files
- foreach ( $files as $file ) {
- if ( is_array( $file ) ) {
+ foreach ( $files as $path ) {
+ if ( is_array( $path ) ) {
// This is a pair, extract it
- list( $zone, $rel ) = $file;
- $root = $this->getZonePath( $zone );
- $path = "$root/$rel";
+ list( $zone, $rel ) = $path;
+ $path = $this->getZonePath( $zone ) . "/$rel";
} else {
- if ( self::isVirtualUrl( $file ) ) {
- // This is a virtual url, resolve it
- $path = $this->resolveVirtualUrl( $file );
- } else {
- // This is a full file name
- $path = $file;
- }
- }
- // Get a file operation if needed
- if ( FileBackend::isStoragePath( $path ) ) {
- $operations[] = array(
- 'op' => 'delete',
- 'src' => $path,
- );
- } else {
- $sourceFSFilesToDelete[] = $path;
+ // Resolve source to a storage path if virtual
+ $path = $this->resolveToStoragePath( $path );
}
+ $operations[] = array( 'op' => 'delete', 'src' => $path );
}
// Actually delete files from storage...
$opts = array( 'force' => true );
if ( $flags & self::SKIP_LOCKING ) {
$opts['nonLocking'] = true;
}
- $this->backend->doOperations( $operations, $opts );
- // Cleanup for disk source files...
- foreach ( $sourceFSFilesToDelete as $file ) {
- wfSuppressWarnings();
- unlink( $file ); // FS cleanup
- wfRestoreWarnings();
+ $status->merge( $this->backend->doOperations( $operations, $opts ) );
+
+ return $status;
+ }
+
+ /**
+ * Import a file from the local file system into the repo.
+ * This does no locking nor journaling and overrides existing files.
+ * This function can be used to write to otherwise read-only foreign repos.
+ * This is intended for copying generated thumbnails into the repo.
+ *
+ * @param $src string Source file system path, storage path, or virtual URL
+ * @param $dst string Virtual URL or storage path
+ * @param $disposition string|null Content-Disposition if given and supported
+ * @return FileRepoStatus
+ */
+ final public function quickImport( $src, $dst, $disposition = null ) {
+ return $this->quickImportBatch( array( array( $src, $dst, $disposition ) ) );
+ }
+
+ /**
+ * Purge a file from the repo. This does no locking nor journaling.
+ * This function can be used to write to otherwise read-only foreign repos.
+ * This is intended for purging thumbnails.
+ *
+ * @param $path string Virtual URL or storage path
+ * @return FileRepoStatus
+ */
+ final public function quickPurge( $path ) {
+ return $this->quickPurgeBatch( array( $path ) );
+ }
+
+ /**
+ * Deletes a directory if empty.
+ * This function can be used to write to otherwise read-only foreign repos.
+ *
+ * @param $dir string Virtual URL (or storage path) of directory to clean
+ * @return Status
+ */
+ public function quickCleanDir( $dir ) {
+ $status = $this->newGood();
+ $status->merge( $this->backend->clean(
+ array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
+
+ return $status;
+ }
+
+ /**
+ * Import a batch of files from the local file system into the repo.
+ * This does no locking nor journaling and overrides existing files.
+ * This function can be used to write to otherwise read-only foreign repos.
+ * This is intended for copying generated thumbnails into the repo.
+ *
+ * All path parameters may be a file system path, storage path, or virtual URL.
+ * When "dispositions" are given they are used as Content-Disposition if supported.
+ *
+ * @param $triples Array List of (source path, destination path, disposition)
+ * @return FileRepoStatus
+ */
+ public function quickImportBatch( array $triples ) {
+ $status = $this->newGood();
+ $operations = array();
+ foreach ( $triples as $triple ) {
+ list( $src, $dst ) = $triple;
+ $src = $this->resolveToStoragePath( $src );
+ $dst = $this->resolveToStoragePath( $dst );
+ $operations[] = array(
+ 'op' => FileBackend::isStoragePath( $src ) ? 'copy' : 'store',
+ 'src' => $src,
+ 'dst' => $dst,
+ 'disposition' => isset( $triple[2] ) ? $triple[2] : null
+ );
+ $status->merge( $this->initDirectory( dirname( $dst ) ) );
}
+ $status->merge( $this->backend->doQuickOperations( $operations ) );
+
+ return $status;
+ }
+
+ /**
+ * Purge a batch of files from the repo.
+ * This function can be used to write to otherwise read-only foreign repos.
+ * This does no locking nor journaling and is intended for purging thumbnails.
+ *
+ * @param $paths Array List of virtual URLs or storage paths
+ * @return FileRepoStatus
+ */
+ public function quickPurgeBatch( array $paths ) {
+ $status = $this->newGood();
+ $operations = array();
+ foreach ( $paths as $path ) {
+ $operations[] = array(
+ 'op' => 'delete',
+ 'src' => $this->resolveToStoragePath( $path ),
+ 'ignoreMissingSource' => true
+ );
+ }
+ $status->merge( $this->backend->doQuickOperations( $operations ) );
+
+ return $status;
}
/**
@@ -784,44 +937,63 @@ class FileRepo {
* Returns a FileRepoStatus object with the file Virtual URL in the value,
* file can later be disposed using FileRepo::freeTemp().
*
- *
* @param $originalName String: the base name of the file as specified
* by the user. The file extension will be maintained.
* @param $srcPath String: the current location of the file.
* @return FileRepoStatus object with the URL in the value.
*/
public function storeTemp( $originalName, $srcPath ) {
- $date = gmdate( "YmdHis" );
- $hashPath = $this->getHashPath( $originalName );
- $dstRel = "{$hashPath}{$date}!{$originalName}";
- $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
+ $this->assertWritableRepo(); // fail out if read-only
+
+ $date = gmdate( "YmdHis" );
+ $hashPath = $this->getHashPath( $originalName );
+ $dstRel = "{$hashPath}{$date}!{$originalName}";
+ $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
+ $virtualUrl = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
+
+ $result = $this->quickImport( $srcPath, $virtualUrl );
+ $result->value = $virtualUrl;
- $result = $this->store( $srcPath, 'temp', $dstRel, self::SKIP_LOCKING );
- $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
return $result;
}
/**
- * Concatenate a list of files into a target file location.
- *
+ * Remove a temporary file or mark it for garbage collection
+ *
+ * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
+ * @return Boolean: true on success, false on failure
+ */
+ public function freeTemp( $virtualUrl ) {
+ $this->assertWritableRepo(); // fail out if read-only
+
+ $temp = $this->getVirtualUrl( 'temp' );
+ if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
+ wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
+ return false;
+ }
+
+ return $this->quickPurge( $virtualUrl )->isOK();
+ }
+
+ /**
+ * Concatenate a list of temporary files into a target file location.
+ *
* @param $srcPaths Array Ordered list of source virtual URLs/storage paths
* @param $dstPath String Target file system path
* @param $flags Integer: bitwise combination of the following flags:
* self::DELETE_SOURCE Delete the source files
* @return FileRepoStatus
*/
- function concatenate( $srcPaths, $dstPath, $flags = 0 ) {
+ public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
+ $this->assertWritableRepo(); // fail out if read-only
+
$status = $this->newGood();
$sources = array();
- $deleteOperations = array(); // post-concatenate ops
foreach ( $srcPaths as $srcPath ) {
// Resolve source to a storage path if virtual
$source = $this->resolveToStoragePath( $srcPath );
$sources[] = $source; // chunk to merge
- if ( $flags & self::DELETE_SOURCE ) {
- $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
- }
}
// Concatenate the chunks into one FS file
@@ -832,50 +1004,34 @@ class FileRepo {
}
// Delete the sources if required
- if ( $deleteOperations ) {
- $opts = array( 'force' => true );
- $status->merge( $this->backend->doOperations( $deleteOperations, $opts ) );
+ if ( $flags & self::DELETE_SOURCE ) {
+ $status->merge( $this->quickPurgeBatch( $srcPaths ) );
}
- // Make sure status is OK, despite any $deleteOperations fatals
+ // Make sure status is OK, despite any quickPurgeBatch() fatals
$status->setResult( true );
return $status;
}
/**
- * Remove a temporary file or mark it for garbage collection
- *
- * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
- * @return Boolean: true on success, false on failure
- */
- public function freeTemp( $virtualUrl ) {
- $temp = "mwrepo://{$this->name}/temp";
- if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
- wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
- return false;
- }
- $path = $this->resolveVirtualUrl( $virtualUrl );
- $op = array( 'op' => 'delete', 'src' => $path );
- $status = $this->backend->doOperation( $op );
- return $status->isOK();
- }
-
- /**
* Copy or move a file either from a storage path, virtual URL,
- * or FS path, into this repository at the specified destination location.
+ * or file system path, into this repository at the specified destination location.
*
* Returns a FileRepoStatus object. On success, the value contains "new" or
* "archived", to indicate whether the file was new with that name.
*
- * @param $srcPath String: the source FS path, storage path, or URL
+ * @param $srcPath String: the source file system path, storage path, or URL
* @param $dstRel String: the destination relative path
* @param $archiveRel String: the relative path where the existing file is to
* be archived, if there is one. Relative to the public zone root.
* @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
* that the source file should be deleted if possible
+ * @return FileRepoStatus
*/
public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
+ $this->assertWritableRepo(); // fail out if read-only
+
$status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
if ( $status->successCount == 0 ) {
$status->ok = false;
@@ -885,6 +1041,7 @@ class FileRepo {
} else {
$status->value = false;
}
+
return $status;
}
@@ -894,11 +1051,13 @@ class FileRepo {
* @param $triplets Array: (source, dest, archive) triplets as per publish()
* @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
* that the source files should be deleted if possible
+ * @throws MWException
* @return FileRepoStatus
*/
- public function publishBatch( $triplets, $flags = 0 ) {
- $backend = $this->backend; // convenience
+ public function publishBatch( array $triplets, $flags = 0 ) {
+ $this->assertWritableRepo(); // fail out if read-only
+ $backend = $this->backend; // convenience
// Try creating directories
$status = $this->initZones( 'public' );
if ( !$status->isOK() ) {
@@ -913,9 +1072,7 @@ class FileRepo {
foreach ( $triplets as $i => $triplet ) {
list( $srcPath, $dstRel, $archiveRel ) = $triplet;
// Resolve source to a storage path if virtual
- if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
- $srcPath = $this->resolveVirtualUrl( $srcPath );
- }
+ $srcPath = $this->resolveToStoragePath( $srcPath );
if ( !$this->validateFilename( $dstRel ) ) {
throw new MWException( 'Validation error in $dstRel' );
}
@@ -930,10 +1087,10 @@ class FileRepo {
$dstDir = dirname( $dstPath );
$archiveDir = dirname( $archivePath );
// Abort immediately on directory creation errors since they're likely to be repetitive
- if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
+ if ( !$this->initDirectory( $dstDir )->isOK() ) {
return $this->newFatal( 'directorycreateerror', $dstDir );
}
- if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
+ if ( !$this->initDirectory($archiveDir )->isOK() ) {
return $this->newFatal( 'directorycreateerror', $archiveDir );
}
@@ -999,15 +1156,50 @@ class FileRepo {
}
/**
+ * Creates a directory with the appropriate zone permissions.
+ * Callers are responsible for doing read-only and "writable repo" checks.
+ *
+ * @param $dir string Virtual URL (or storage path) of directory to clean
+ * @return Status
+ */
+ protected function initDirectory( $dir ) {
+ $path = $this->resolveToStoragePath( $dir );
+ list( $b, $container, $r ) = FileBackend::splitStoragePath( $path );
+
+ $params = array( 'dir' => $path );
+ if ( $this->isPrivate || $container === $this->zones['deleted']['container'] ) {
+ # Take all available measures to prevent web accessibility of new deleted
+ # directories, in case the user has not configured offline storage
+ $params = array( 'noAccess' => true, 'noListing' => true ) + $params;
+ }
+
+ return $this->backend->prepare( $params );
+ }
+
+ /**
+ * Deletes a directory if empty.
+ *
+ * @param $dir string Virtual URL (or storage path) of directory to clean
+ * @return Status
+ */
+ public function cleanDir( $dir ) {
+ $this->assertWritableRepo(); // fail out if read-only
+
+ $status = $this->newGood();
+ $status->merge( $this->backend->clean(
+ array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
+
+ return $status;
+ }
+
+ /**
* Checks existence of a a file
*
- * @param $file Virtual URL (or storage path) of file to check
- * @param $flags Integer: bitwise combination of the following flags:
- * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
+ * @param $file string Virtual URL (or storage path) of file to check
* @return bool
*/
- public function fileExists( $file, $flags = 0 ) {
- $result = $this->fileExistsBatch( array( $file ), $flags );
+ public function fileExists( $file ) {
+ $result = $this->fileExistsBatch( array( $file ) );
return $result[0];
}
@@ -1015,27 +1207,14 @@ class FileRepo {
* Checks existence of an array of files.
*
* @param $files Array: Virtual URLs (or storage paths) of files to check
- * @param $flags Integer: bitwise combination of the following flags:
- * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
- * @return Either array of files and existence flags, or false
+ * @return array|bool Either array of files and existence flags, or false
*/
- public function fileExistsBatch( $files, $flags = 0 ) {
+ public function fileExistsBatch( array $files ) {
$result = array();
foreach ( $files as $key => $file ) {
- if ( self::isVirtualUrl( $file ) ) {
- $file = $this->resolveVirtualUrl( $file );
- }
- if ( FileBackend::isStoragePath( $file ) ) {
- $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
- } else {
- if ( $flags & self::FILES_ONLY ) {
- $result[$key] = is_file( $file ); // FS only
- } else {
- $result[$key] = file_exists( $file ); // FS only
- }
- }
+ $file = $this->resolveToStoragePath( $file );
+ $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
}
-
return $result;
}
@@ -1050,6 +1229,8 @@ class FileRepo {
* @return FileRepoStatus object
*/
public function delete( $srcRel, $archiveRel ) {
+ $this->assertWritableRepo(); // fail out if read-only
+
return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
}
@@ -1067,10 +1248,11 @@ class FileRepo {
* is a two-element array containing the source file path relative to the
* public root in the first element, and the archive file path relative
* to the deleted zone root in the second element.
+ * @throws MWException
* @return FileRepoStatus
*/
- public function deleteBatch( $sourceDestPairs ) {
- $backend = $this->backend; // convenience
+ public function deleteBatch( array $sourceDestPairs ) {
+ $this->assertWritableRepo(); // fail out if read-only
// Try creating directories
$status = $this->initZones( array( 'public', 'deleted' ) );
@@ -1080,14 +1262,14 @@ class FileRepo {
$status = $this->newGood();
+ $backend = $this->backend; // convenience
$operations = array();
// Validate filenames and create archive directories
foreach ( $sourceDestPairs as $pair ) {
list( $srcRel, $archiveRel ) = $pair;
if ( !$this->validateFilename( $srcRel ) ) {
throw new MWException( __METHOD__.':Validation error in $srcRel' );
- }
- if ( !$this->validateFilename( $archiveRel ) ) {
+ } elseif ( !$this->validateFilename( $archiveRel ) ) {
throw new MWException( __METHOD__.':Validation error in $archiveRel' );
}
@@ -1099,10 +1281,9 @@ class FileRepo {
$archiveDir = dirname( $archivePath ); // does not touch FS
// Create destination directories
- if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
+ if ( !$this->initDirectory( $archiveDir )->isOK() ) {
return $this->newFatal( 'directorycreateerror', $archiveDir );
}
- $this->initDeletedDir( $archiveDir );
$operations[] = array(
'op' => 'move',
@@ -1124,9 +1305,19 @@ class FileRepo {
}
/**
+ * Delete files in the deleted directory if they are not referenced in the filearchive table
+ *
+ * STUB
+ */
+ public function cleanupDeletedBatch( array $storageKeys ) {
+ $this->assertWritableRepo();
+ }
+
+ /**
* Get a relative path for a deletion archive key,
* e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
*
+ * @param $key string
* @return string
*/
public function getDeletedHashPath( $key ) {
@@ -1155,7 +1346,7 @@ class FileRepo {
/**
* Get a local FS copy of a file with a given virtual URL/storage path.
* Temporary files may be purged when the file object falls out of scope.
- *
+ *
* @param $virtualUrl string
* @return TempFSFile|null Returns null on failure
*/
@@ -1168,7 +1359,7 @@ class FileRepo {
* Get a local FS file with a given virtual URL/storage path.
* The file is either an original or a copy. It should not be changed.
* Temporary files may be purged when the file object falls out of scope.
- *
+ *
* @param $virtualUrl string
* @return FSFile|null Returns null on failure.
*/
@@ -1193,7 +1384,7 @@ class FileRepo {
* Get the timestamp of a file with a given virtual URL/storage path
*
* @param $virtualUrl string
- * @return string|false
+ * @return string|bool False on failure
*/
public function getFileTimestamp( $virtualUrl ) {
$path = $this->resolveToStoragePath( $virtualUrl );
@@ -1201,18 +1392,14 @@ class FileRepo {
}
/**
- * Get the sha1 of a file with a given virtual URL/storage path
+ * Get the sha1 (base 36) of a file with a given virtual URL/storage path
*
* @param $virtualUrl string
- * @return string|false
+ * @return string|bool
*/
public function getFileSha1( $virtualUrl ) {
$path = $this->resolveToStoragePath( $virtualUrl );
- $tmpFile = $this->backend->getLocalReference( array( 'src' => $path ) );
- if ( !$tmpFile ) {
- return false;
- }
- return $tmpFile->getSha1Base36();
+ return $this->backend->getFileSha1Base36( array( 'src' => $path ) );
}
/**
@@ -1276,23 +1463,7 @@ class FileRepo {
if ( strval( $filename ) == '' ) {
return false;
}
- if ( wfIsWindows() ) {
- $filename = strtr( $filename, '\\', '/' );
- }
- /**
- * Use the same traversal protection as Title::secureAndSplit()
- */
- if ( strpos( $filename, '.' ) !== false &&
- ( $filename === '.' || $filename === '..' ||
- strpos( $filename, './' ) === 0 ||
- strpos( $filename, '../' ) === 0 ||
- strpos( $filename, '/./' ) !== false ||
- strpos( $filename, '/../' ) !== false ) )
- {
- return false;
- } else {
- return true;
- }
+ return FileBackend::isPathTraversalFree( $filename );
}
/**
@@ -1303,11 +1474,9 @@ class FileRepo {
function getErrorCleanupFunction() {
switch ( $this->pathDisclosureProtection ) {
case 'none':
+ case 'simple': // b/c
$callback = array( $this, 'passThrough' );
break;
- case 'simple':
- $callback = array( $this, 'simpleClean' );
- break;
default: // 'paranoid'
$callback = array( $this, 'paranoidClean' );
}
@@ -1330,22 +1499,6 @@ class FileRepo {
* @param $param string
* @return string
*/
- function simpleClean( $param ) {
- global $IP;
- if ( !isset( $this->simpleCleanPairs ) ) {
- $this->simpleCleanPairs = array(
- $IP => '$IP', // sanity
- );
- }
- return strtr( $param, $this->simpleCleanPairs );
- }
-
- /**
- * Path disclosure protection function
- *
- * @param $param string
- * @return string
- */
function passThrough( $param ) {
return $param;
}
@@ -1355,7 +1508,7 @@ class FileRepo {
*
* @return FileRepoStatus
*/
- function newFatal( $message /*, parameters...*/ ) {
+ public function newFatal( $message /*, parameters...*/ ) {
$params = func_get_args();
array_unshift( $params, $this );
return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
@@ -1364,20 +1517,14 @@ class FileRepo {
/**
* Create a new good result
*
+ * @param $value null|string
* @return FileRepoStatus
*/
- function newGood( $value = null ) {
+ public function newGood( $value = null ) {
return FileRepoStatus::newGood( $this, $value );
}
/**
- * Delete files in the deleted directory if they are not referenced in the filearchive table
- *
- * STUB
- */
- public function cleanupDeletedBatch( $storageKeys ) {}
-
- /**
* Checks if there is a redirect named as $title. If there is, return the
* title object. If not, return false.
* STUB
@@ -1413,6 +1560,21 @@ class FileRepo {
}
/**
+ * Get the portion of the file that contains the origin file name.
+ * If that name is too long, then the name "thumbnail.<ext>" will be given.
+ *
+ * @param $name string
+ * @return string
+ */
+ public function nameForThumb( $name ) {
+ if ( strlen( $name ) > $this->abbrvThreshold ) {
+ $ext = FileBackend::extensionFromPath( $name );
+ $name = ( $ext == '' ) ? 'thumbnail' : "thumbnail.$ext";
+ }
+ return $name;
+ }
+
+ /**
* Returns true if this the local file repository.
*
* @return bool
@@ -1427,8 +1589,9 @@ class FileRepo {
* The parameters are the parts of the key, as for wfMemcKey().
*
* STUB
+ * @return bool
*/
- function getSharedCacheKey( /*...*/ ) {
+ public function getSharedCacheKey( /*...*/ ) {
return false;
}
@@ -1439,13 +1602,43 @@ class FileRepo {
*
* @return string
*/
- function getLocalCacheKey( /*...*/ ) {
+ public function getLocalCacheKey( /*...*/ ) {
$args = func_get_args();
array_unshift( $args, 'filerepo', $this->getName() );
return call_user_func_array( 'wfMemcKey', $args );
}
/**
+ * Get an temporary FileRepo associated with this repo.
+ * Files will be created in the temp zone of this repo and
+ * thumbnails in a /temp subdirectory in thumb zone of this repo.
+ * It will have the same backend as this repo.
+ *
+ * @return TempFileRepo
+ */
+ public function getTempRepo() {
+ return new TempFileRepo( array(
+ 'name' => "{$this->name}-temp",
+ 'backend' => $this->backend,
+ 'zones' => array(
+ 'public' => array(
+ 'container' => $this->zones['temp']['container'],
+ 'directory' => $this->zones['temp']['directory']
+ ),
+ 'thumb' => array(
+ 'container' => $this->zones['thumb']['container'],
+ 'directory' => ( $this->zones['thumb']['directory'] == '' )
+ ? 'temp'
+ : $this->zones['thumb']['directory'] . '/temp'
+ )
+ ),
+ 'url' => $this->getZoneUrl( 'temp' ),
+ 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
+ 'hashLevels' => $this->hashLevels // performance
+ ) );
+ }
+
+ /**
* Get an UploadStash associated with this repo.
*
* @return UploadStash
@@ -1453,4 +1646,22 @@ class FileRepo {
public function getUploadStash() {
return new UploadStash( $this );
}
+
+ /**
+ * Throw an exception if this repo is read-only by design.
+ * This does not and should not check getReadOnlyReason().
+ *
+ * @return void
+ * @throws MWException
+ */
+ protected function assertWritableRepo() {}
+}
+
+/**
+ * FileRepo for temporary files created via FileRepo::getTempRepo()
+ */
+class TempFileRepo extends FileRepo {
+ public function getTempRepo() {
+ throw new MWException( "Cannot get a temp repo from a temp repo." );
+ }
}
diff --git a/includes/filerepo/FileRepoStatus.php b/includes/filerepo/FileRepoStatus.php
index 4eea9030..6f28b104 100644
--- a/includes/filerepo/FileRepoStatus.php
+++ b/includes/filerepo/FileRepoStatus.php
@@ -1,6 +1,21 @@
<?php
/**
- * Generic operation result for FileRepo-related operations
+ * Generic operation result for FileRepo-related operations.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileRepo
diff --git a/includes/filerepo/ForeignAPIRepo.php b/includes/filerepo/ForeignAPIRepo.php
index e544defb..13de9e6b 100644
--- a/includes/filerepo/ForeignAPIRepo.php
+++ b/includes/filerepo/ForeignAPIRepo.php
@@ -2,6 +2,21 @@
/**
* Foreign repository accessible through api.php requests.
*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
* @file
* @ingroup FileRepo
*/
@@ -36,6 +51,9 @@ class ForeignAPIRepo extends FileRepo {
protected $mQueryCache = array();
protected $mFileExists = array();
+ /**
+ * @param $info array|null
+ */
function __construct( $info ) {
global $wgLocalFileRepo;
parent::__construct( $info );
@@ -66,6 +84,8 @@ class ForeignAPIRepo extends FileRepo {
* Per docs in FileRepo, this needs to return false if we don't support versioned
* files. Well, we don't.
*
+ * @param $title Title
+ * @param $time string|bool
* @return File
*/
function newFile( $title, $time = false ) {
@@ -76,38 +96,10 @@ class ForeignAPIRepo extends FileRepo {
}
/**
- * No-ops
+ * @param $files array
+ * @return array
*/
-
- function storeBatch( $triplets, $flags = 0 ) {
- return false;
- }
-
- function storeTemp( $originalName, $srcPath ) {
- return false;
- }
-
- function concatenate( $fileList, $targetPath, $flags = 0 ){
- return false;
- }
-
- function append( $srcPath, $toAppendPath, $flags = 0 ){
- return false;
- }
-
- function appendFinish( $toAppendPath ){
- return false;
- }
-
- function publishBatch( $triplets, $flags = 0 ) {
- return false;
- }
-
- function deleteBatch( $sourceDestPairs ) {
- return false;
- }
-
- function fileExistsBatch( $files, $flags = 0 ) {
+ function fileExistsBatch( array $files ) {
$results = array();
foreach ( $files as $k => $f ) {
if ( isset( $this->mFileExists[$k] ) ) {
@@ -119,6 +111,10 @@ class ForeignAPIRepo extends FileRepo {
# same repo.
$results[$k] = false;
unset( $files[$k] );
+ } elseif ( FileBackend::isStoragePath( $f ) ) {
+ $results[$k] = false;
+ unset( $files[$k] );
+ wfWarn( "Got mwstore:// path '$f'." );
}
}
@@ -134,17 +130,25 @@ class ForeignAPIRepo extends FileRepo {
return $results;
}
+ /**
+ * @param $virtualUrl string
+ * @return bool
+ */
function getFileProps( $virtualUrl ) {
return false;
}
+ /**
+ * @param $query array
+ * @return string
+ */
function fetchImageQuery( $query ) {
global $wgMemc;
$query = array_merge( $query,
array(
- 'format' => 'json',
- 'action' => 'query',
+ 'format' => 'json',
+ 'action' => 'query',
'redirects' => 'true'
) );
if ( $this->mApiBase ) {
@@ -173,6 +177,10 @@ class ForeignAPIRepo extends FileRepo {
return FormatJson::decode( $this->mQueryCache[$url], true );
}
+ /**
+ * @param $data array
+ * @return bool|array
+ */
function getImageInfo( $data ) {
if( $data && isset( $data['query']['pages'] ) ) {
foreach( $data['query']['pages'] as $info ) {
@@ -184,6 +192,10 @@ class ForeignAPIRepo extends FileRepo {
return false;
}
+ /**
+ * @param $hash string
+ * @return array
+ */
function findBySha1( $hash ) {
$results = $this->fetchImageQuery( array(
'aisha1base36' => $hash,
@@ -202,6 +214,14 @@ class ForeignAPIRepo extends FileRepo {
return $ret;
}
+ /**
+ * @param $name string
+ * @param $width int
+ * @param $height int
+ * @param $result null
+ * @param $otherParams string
+ * @return bool
+ */
function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
$data = $this->fetchImageQuery( array(
'titles' => 'File:' . $name,
@@ -230,10 +250,14 @@ class ForeignAPIRepo extends FileRepo {
* @param $name String is a dbkey form of a title
* @param $width
* @param $height
- * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
+ * @param String $params Other rendering parameters (page number, etc) from handler's makeParamString.
+ * @return bool|string
*/
- function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
+ function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
global $wgMemc;
+ // We can't check the local cache using FileRepo functions because
+ // we override fileExistsBatch(). We have to use the FileBackend directly.
+ $backend = $this->getBackend(); // convenience
if ( !$this->canCacheThumbs() ) {
$result = null; // can't pass "null" by reference, but it's ok as default value
@@ -274,9 +298,11 @@ class ForeignAPIRepo extends FileRepo {
$localFilename = $localPath . "/" . $fileName;
$localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
- if( $this->fileExists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
+ if( $backend->fileExists( array( 'src' => $localFilename ) )
+ && isset( $metadata['timestamp'] ) )
+ {
wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
- $modified = $this->getFileTimestamp( $localFilename );
+ $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
$remoteModified = strtotime( $metadata['timestamp'] );
$current = time();
$diff = abs( $modified - $current );
@@ -294,16 +320,14 @@ class ForeignAPIRepo extends FileRepo {
return false;
}
+
# @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
- wfSuppressWarnings();
- $backend = $this->getBackend();
- $op = array( 'op' => 'create', 'dst' => $localFilename, 'content' => $thumb );
- if( !$backend->doOperation( $op )->isOK() ) {
- wfRestoreWarnings();
- wfDebug( __METHOD__ . " could not write to thumb path\n" );
+ $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
+ $params = array( 'dst' => $localFilename, 'content' => $thumb );
+ if( !$backend->quickCreate( $params )->isOK() ) {
+ wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'\n" );
return $foreignUrl;
}
- wfRestoreWarnings();
$knownThumbUrls[$sizekey] = $localUrl;
$wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
@@ -312,6 +336,8 @@ class ForeignAPIRepo extends FileRepo {
/**
* @see FileRepo::getZoneUrl()
+ * @param $zone String
+ * @return String
*/
function getZoneUrl( $zone ) {
switch ( $zone ) {
@@ -326,6 +352,8 @@ class ForeignAPIRepo extends FileRepo {
/**
* Get the local directory corresponding to one of the basic zones
+ * @param $zone string
+ * @return bool|null|string
*/
function getZonePath( $zone ) {
$supported = array( 'public', 'thumb' );
@@ -345,6 +373,7 @@ class ForeignAPIRepo extends FileRepo {
/**
* The user agent the ForeignAPIRepo will use.
+ * @return string
*/
public static function getUserAgent() {
return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
@@ -353,6 +382,10 @@ class ForeignAPIRepo extends FileRepo {
/**
* Like a Http:get request, but with custom User-Agent.
* @see Http:get
+ * @param $url string
+ * @param $timeout string
+ * @param $options array
+ * @return bool|String
*/
public static function httpGet( $url, $timeout = 'default', $options = array() ) {
$options['timeout'] = $timeout;
@@ -362,7 +395,7 @@ class ForeignAPIRepo extends FileRepo {
$options['method'] = "GET";
if ( !isset( $options['timeout'] ) ) {
- $options['timeout'] = 'default';
+ $options['timeout'] = 'default';
}
$req = MWHttpRequest::factory( $url, $options );
@@ -370,13 +403,24 @@ class ForeignAPIRepo extends FileRepo {
$status = $req->execute();
if ( $status->isOK() ) {
- return $req->getContent();
+ return $req->getContent();
} else {
- return false;
+ return false;
}
}
+ /**
+ * @param $callback Array|string
+ * @throws MWException
+ */
function enumFiles( $callback ) {
throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
}
+
+ /**
+ * @throws MWException
+ */
+ protected function assertWritableRepo() {
+ throw new MWException( get_class( $this ) . ': write operations are not supported.' );
+ }
}
diff --git a/includes/filerepo/ForeignDBRepo.php b/includes/filerepo/ForeignDBRepo.php
index 0311ebcd..4b206c3d 100644
--- a/includes/filerepo/ForeignDBRepo.php
+++ b/includes/filerepo/ForeignDBRepo.php
@@ -1,6 +1,21 @@
<?php
/**
- * A foreign repository with an accessible MediaWiki database
+ * A foreign repository with an accessible MediaWiki database.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileRepo
@@ -21,6 +36,9 @@ class ForeignDBRepo extends LocalRepo {
var $fileFactory = array( 'ForeignDBFile', 'newFromTitle' );
var $fileFromRowFactory = array( 'ForeignDBFile', 'newFromRow' );
+ /**
+ * @param $info array|null
+ */
function __construct( $info ) {
parent::__construct( $info );
$this->dbType = $info['dbType'];
@@ -33,6 +51,9 @@ class ForeignDBRepo extends LocalRepo {
$this->hasSharedCache = $info['hasSharedCache'];
}
+ /**
+ * @return DatabaseBase
+ */
function getMasterDB() {
if ( !isset( $this->dbConn ) ) {
$this->dbConn = DatabaseBase::factory( $this->dbType,
@@ -49,10 +70,16 @@ class ForeignDBRepo extends LocalRepo {
return $this->dbConn;
}
+ /**
+ * @return DatabaseBase
+ */
function getSlaveDB() {
return $this->getMasterDB();
}
+ /**
+ * @return bool
+ */
function hasSharedCache() {
return $this->hasSharedCache;
}
@@ -61,6 +88,7 @@ class ForeignDBRepo extends LocalRepo {
* Get a key on the primary cache for this repository.
* Returns false if the repository's cache is not accessible at this site.
* The parameters are the parts of the key, as for wfMemcKey().
+ * @return bool|mixed
*/
function getSharedCacheKey( /*...*/ ) {
if ( $this->hasSharedCache() ) {
@@ -72,13 +100,7 @@ class ForeignDBRepo extends LocalRepo {
}
}
- function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
- throw new MWException( get_class($this) . ': write operations are not supported' );
- }
- function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
- throw new MWException( get_class($this) . ': write operations are not supported' );
- }
- function deleteBatch( $sourceDestPairs ) {
- throw new MWException( get_class($this) . ': write operations are not supported' );
+ protected function assertWritableRepo() {
+ throw new MWException( get_class( $this ) . ': write operations are not supported.' );
}
}
diff --git a/includes/filerepo/ForeignDBViaLBRepo.php b/includes/filerepo/ForeignDBViaLBRepo.php
index 28b48b5e..bd76fce7 100644
--- a/includes/filerepo/ForeignDBViaLBRepo.php
+++ b/includes/filerepo/ForeignDBViaLBRepo.php
@@ -1,6 +1,21 @@
<?php
/**
- * A foreign repository with a MediaWiki database accessible via the configured LBFactory
+ * A foreign repository with a MediaWiki database accessible via the configured LBFactory.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileRepo
@@ -16,6 +31,9 @@ class ForeignDBViaLBRepo extends LocalRepo {
var $fileFactory = array( 'ForeignDBFile', 'newFromTitle' );
var $fileFromRowFactory = array( 'ForeignDBFile', 'newFromRow' );
+ /**
+ * @param $info array|null
+ */
function __construct( $info ) {
parent::__construct( $info );
$this->wiki = $info['wiki'];
@@ -23,10 +41,16 @@ class ForeignDBViaLBRepo extends LocalRepo {
$this->hasSharedCache = $info['hasSharedCache'];
}
+ /**
+ * @return DatabaseBase
+ */
function getMasterDB() {
return wfGetDB( DB_MASTER, array(), $this->wiki );
}
+ /**
+ * @return DatabaseBase
+ */
function getSlaveDB() {
return wfGetDB( DB_SLAVE, array(), $this->wiki );
}
@@ -39,6 +63,7 @@ class ForeignDBViaLBRepo extends LocalRepo {
* Get a key on the primary cache for this repository.
* Returns false if the repository's cache is not accessible at this site.
* The parameters are the parts of the key, as for wfMemcKey().
+ * @return bool|string
*/
function getSharedCacheKey( /*...*/ ) {
if ( $this->hasSharedCache() ) {
@@ -50,13 +75,7 @@ class ForeignDBViaLBRepo extends LocalRepo {
}
}
- function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
- throw new MWException( get_class($this) . ': write operations are not supported' );
- }
- function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
- throw new MWException( get_class($this) . ': write operations are not supported' );
- }
- function deleteBatch( $fileMap ) {
- throw new MWException( get_class($this) . ': write operations are not supported' );
+ protected function assertWritableRepo() {
+ throw new MWException( get_class( $this ) . ': write operations are not supported.' );
}
}
diff --git a/includes/filerepo/LocalRepo.php b/includes/filerepo/LocalRepo.php
index cc23fa31..0954422d 100644
--- a/includes/filerepo/LocalRepo.php
+++ b/includes/filerepo/LocalRepo.php
@@ -3,6 +3,21 @@
* Local repository that stores files in the local filesystem and registers them
* in the wiki's own database.
*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
* @file
* @ingroup FileRepo
*/
@@ -24,7 +39,7 @@ class LocalRepo extends FileRepo {
/**
* @throws MWException
* @param $row
- * @return File
+ * @return LocalFile
*/
function newFileFromRow( $row ) {
if ( isset( $row->img_name ) ) {
@@ -55,7 +70,7 @@ class LocalRepo extends FileRepo {
*
* @return FileRepoStatus
*/
- function cleanupDeletedBatch( $storageKeys ) {
+ function cleanupDeletedBatch( array $storageKeys ) {
$backend = $this->backend; // convenience
$root = $this->getZonePath( 'deleted' );
$dbw = $this->getMasterDB();
@@ -64,7 +79,7 @@ class LocalRepo extends FileRepo {
foreach ( $storageKeys as $key ) {
$hashPath = $this->getDeletedHashPath( $key );
$path = "$root/$hashPath$key";
- $dbw->begin();
+ $dbw->begin( __METHOD__ );
// Check for usage in deleted/hidden files and pre-emptively
// lock the key to avoid any future use until we are finished.
$deleted = $this->deletedFileHasKey( $key, 'lock' );
@@ -80,7 +95,7 @@ class LocalRepo extends FileRepo {
wfDebug( __METHOD__ . ": $key still in use\n" );
$status->successCount++;
}
- $dbw->commit();
+ $dbw->commit( __METHOD__ );
}
return $status;
}
@@ -133,7 +148,7 @@ class LocalRepo extends FileRepo {
public static function getHashFromKey( $key ) {
return strtok( $key, '.' );
}
-
+
/**
* Checks if there is a redirect named as $title
*
@@ -183,12 +198,12 @@ class LocalRepo extends FileRepo {
}
}
-
/**
* Function link Title::getArticleID().
* We can't say Title object, what database it should use, so we duplicate that function here.
*
* @param $title Title
+ * @return bool|int|mixed
*/
protected function getArticleID( $title ) {
if( !$title instanceof Title ) {
@@ -219,7 +234,9 @@ class LocalRepo extends FileRepo {
$res = $dbr->select(
'image',
LocalFile::selectFields(),
- array( 'img_sha1' => $hash )
+ array( 'img_sha1' => $hash ),
+ __METHOD__,
+ array( 'ORDER BY' => 'img_name' )
);
$result = array();
@@ -232,7 +249,41 @@ class LocalRepo extends FileRepo {
}
/**
+ * Get an array of arrays or iterators of file objects for files that
+ * have the given SHA-1 content hashes.
+ *
+ * Overrides generic implementation in FileRepo for performance reason
+ *
+ * @param $hashes array An array of hashes
+ * @return array An Array of arrays or iterators of file objects and the hash as key
+ */
+ function findBySha1s( array $hashes ) {
+ if( !count( $hashes ) ) {
+ return array(); //empty parameter
+ }
+
+ $dbr = $this->getSlaveDB();
+ $res = $dbr->select(
+ 'image',
+ LocalFile::selectFields(),
+ array( 'img_sha1' => $hashes ),
+ __METHOD__,
+ array( 'ORDER BY' => 'img_name' )
+ );
+
+ $result = array();
+ foreach ( $res as $row ) {
+ $file = $this->newFileFromRow( $row );
+ $result[$file->getSha1()][] = $file;
+ }
+ $res->free();
+
+ return $result;
+ }
+
+ /**
* Get a connection to the slave DB
+ * @return DatabaseBase
*/
function getSlaveDB() {
return wfGetDB( DB_SLAVE );
@@ -240,6 +291,7 @@ class LocalRepo extends FileRepo {
/**
* Get a connection to the master DB
+ * @return DatabaseBase
*/
function getMasterDB() {
return wfGetDB( DB_MASTER );
diff --git a/includes/filerepo/NullRepo.php b/includes/filerepo/NullRepo.php
index 65318f40..dda51cea 100644
--- a/includes/filerepo/NullRepo.php
+++ b/includes/filerepo/NullRepo.php
@@ -2,6 +2,21 @@
/**
* File repository with no files.
*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
* @file
* @ingroup FileRepo
*/
@@ -11,40 +26,13 @@
* @ingroup FileRepo
*/
class NullRepo extends FileRepo {
- function __construct( $info ) {}
- function storeBatch( $triplets, $flags = 0 ) {
- return false;
- }
+ /**
+ * @param $info array|null
+ */
+ function __construct( $info ) {}
- function storeTemp( $originalName, $srcPath ) {
- return false;
- }
- function append( $srcPath, $toAppendPath, $flags = 0 ){
- return false;
- }
- function appendFinish( $toAppendPath ){
- return false;
- }
- function publishBatch( $triplets, $flags = 0 ) {
- return false;
- }
- function deleteBatch( $sourceDestPairs ) {
- return false;
- }
- function fileExistsBatch( $files, $flags = 0 ) {
- return false;
- }
- function getFileProps( $virtualUrl ) {
- return false;
- }
- function newFile( $title, $time = false ) {
- return false;
- }
- function findFile( $title, $options = array() ) {
- return false;
- }
- function concatenate( $fileList, $targetPath, $flags = 0 ) {
- return false;
+ protected function assertWritableRepo() {
+ throw new MWException( get_class( $this ) . ': write operations are not supported.' );
}
}
diff --git a/includes/filerepo/RepoGroup.php b/includes/filerepo/RepoGroup.php
index 334ef2b8..f9e57599 100644
--- a/includes/filerepo/RepoGroup.php
+++ b/includes/filerepo/RepoGroup.php
@@ -1,6 +1,21 @@
<?php
/**
- * Prioritized list of file repositories
+ * Prioritized list of file repositories.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileRepo
@@ -12,7 +27,6 @@
* @ingroup FileRepo
*/
class RepoGroup {
-
/**
* @var LocalRepo
*/
@@ -26,7 +40,7 @@ class RepoGroup {
* @var RepoGroup
*/
protected static $instance;
- const MAX_CACHE_SIZE = 1000;
+ const MAX_CACHE_SIZE = 500;
/**
* Get a RepoGroup instance. At present only one instance of RepoGroup is
@@ -65,7 +79,7 @@ class RepoGroup {
/**
* Construct a group of file repositories.
*
- * @param $localInfo Associative array for local repo's info
+ * @param $localInfo array Associative array for local repo's info
* @param $foreignInfo Array of repository info arrays.
* Each info array is an associative array with the 'class' member
* giving the class name. The entire array is passed to the repository
@@ -114,50 +128,47 @@ class RepoGroup {
&& empty( $options['private'] )
&& empty( $options['bypassCache'] ) )
{
- $useCache = true;
$time = isset( $options['time'] ) ? $options['time'] : '';
$dbkey = $title->getDBkey();
if ( isset( $this->cache[$dbkey][$time] ) ) {
wfDebug( __METHOD__.": got File:$dbkey from process cache\n" );
# Move it to the end of the list so that we can delete the LRU entry later
- $tmp = $this->cache[$dbkey];
- unset( $this->cache[$dbkey] );
- $this->cache[$dbkey] = $tmp;
+ $this->pingCache( $dbkey );
# Return the entry
return $this->cache[$dbkey][$time];
- } else {
- # Add a negative cache entry, may be overridden
- $this->trimCache();
- $this->cache[$dbkey][$time] = false;
- $cacheEntry =& $this->cache[$dbkey][$time];
}
+ $useCache = true;
} else {
$useCache = false;
}
# Check the local repo
$image = $this->localRepo->findFile( $title, $options );
- if ( $image ) {
- if ( $useCache ) {
- $cacheEntry = $image;
- }
- return $image;
- }
# Check the foreign repos
- foreach ( $this->foreignRepos as $repo ) {
- $image = $repo->findFile( $title, $options );
- if ( $image ) {
- if ( $useCache ) {
- $cacheEntry = $image;
+ if ( !$image ) {
+ foreach ( $this->foreignRepos as $repo ) {
+ $image = $repo->findFile( $title, $options );
+ if ( $image ) {
+ break;
}
- return $image;
}
}
- # Not found, do not override negative cache
- return false;
+
+ $image = $image ? $image : false; // type sanity
+ # Cache file existence or non-existence
+ if ( $useCache && ( !$image || $image->isCacheable() ) ) {
+ $this->trimCache();
+ $this->cache[$dbkey][$time] = $image;
+ }
+
+ return $image;
}
+ /**
+ * @param $inputItems array
+ * @return array
+ */
function findFiles( $inputItems ) {
if ( !$this->reposInitialised ) {
$this->initialiseRepos();
@@ -189,6 +200,8 @@ class RepoGroup {
/**
* Interface for FileRepo::checkRedirect()
+ * @param $title Title
+ * @return bool
*/
function checkRedirect( Title $title ) {
if ( !$this->reposInitialised ) {
@@ -213,7 +226,7 @@ class RepoGroup {
* Returns false if the file does not exist.
*
* @param $hash String base 36 SHA-1 hash
- * @param $options Option array, same as findFile()
+ * @param $options array Option array, same as findFile()
* @return File object or false if it is not found
*/
function findFileFromKey( $hash, $options = array() ) {
@@ -246,11 +259,36 @@ class RepoGroup {
foreach ( $this->foreignRepos as $repo ) {
$result = array_merge( $result, $repo->findBySha1( $hash ) );
}
+ usort( $result, 'File::compare' );
+ return $result;
+ }
+
+ /**
+ * Find all instances of files with this keys
+ *
+ * @param $hashes Array base 36 SHA-1 hashes
+ * @return Array of array of File objects
+ */
+ function findBySha1s( array $hashes ) {
+ if ( !$this->reposInitialised ) {
+ $this->initialiseRepos();
+ }
+
+ $result = $this->localRepo->findBySha1s( $hashes );
+ foreach ( $this->foreignRepos as $repo ) {
+ $result = array_merge_recursive( $result, $repo->findBySha1s( $hashes ) );
+ }
+ //sort the merged (and presorted) sublist of each hash
+ foreach( $result as $hash => $files ) {
+ usort( $result[$hash], 'File::compare' );
+ }
return $result;
}
/**
* Get the repo instance with a given key.
+ * @param $index string|int
+ * @return bool|LocalRepo
*/
function getRepo( $index ) {
if ( !$this->reposInitialised ) {
@@ -264,16 +302,20 @@ class RepoGroup {
return false;
}
}
+
/**
* Get the repo instance by its name
+ * @param $name string
+ * @return bool
*/
function getRepoByName( $name ) {
if ( !$this->reposInitialised ) {
$this->initialiseRepos();
}
foreach ( $this->foreignRepos as $repo ) {
- if ( $repo->name == $name)
+ if ( $repo->name == $name ) {
return $repo;
+ }
}
return false;
}
@@ -294,6 +336,7 @@ class RepoGroup {
*
* @param $callback Callback: the function to call
* @param $params Array: optional additional parameters to pass to the function
+ * @return bool
*/
function forEachForeignRepo( $callback, $params = array() ) {
foreach( $this->foreignRepos as $repo ) {
@@ -339,7 +382,9 @@ class RepoGroup {
/**
* Split a virtual URL into repo, zone and rel parts
- * @return an array containing repo, zone and rel
+ * @param $url string
+ * @throws MWException
+ * @return array containing repo, zone and rel
*/
function splitVirtualUrl( $url ) {
if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
@@ -353,6 +398,10 @@ class RepoGroup {
return $bits;
}
+ /**
+ * @param $fileName string
+ * @return array
+ */
function getFileProps( $fileName ) {
if ( FileRepo::isVirtualUrl( $fileName ) ) {
list( $repoName, /* $zone */, /* $rel */ ) = $this->splitVirtualUrl( $fileName );
@@ -367,6 +416,17 @@ class RepoGroup {
}
/**
+ * Move a cache entry to the top (such as when accessed)
+ */
+ protected function pingCache( $key ) {
+ if ( isset( $this->cache[$key] ) ) {
+ $tmp = $this->cache[$key];
+ unset( $this->cache[$key] );
+ $this->cache[$key] = $tmp;
+ }
+ }
+
+ /**
* Limit cache memory
*/
protected function trimCache() {
diff --git a/includes/filerepo/backend/FSFile.php b/includes/filerepo/backend/FSFile.php
deleted file mode 100644
index 54dd1359..00000000
--- a/includes/filerepo/backend/FSFile.php
+++ /dev/null
@@ -1,233 +0,0 @@
-<?php
-/**
- * @file
- * @ingroup FileBackend
- */
-
-/**
- * Class representing a non-directory file on the file system
- *
- * @ingroup FileBackend
- */
-class FSFile {
- protected $path; // path to file
-
- /**
- * Sets up the file object
- *
- * @param String $path Path to temporary file on local disk
- */
- public function __construct( $path ) {
- if ( FileBackend::isStoragePath( $path ) ) {
- throw new MWException( __METHOD__ . " given storage path `$path`." );
- }
- $this->path = $path;
- }
-
- /**
- * Returns the file system path
- *
- * @return String
- */
- public function getPath() {
- return $this->path;
- }
-
- /**
- * Checks if the file exists
- *
- * @return bool
- */
- public function exists() {
- return is_file( $this->path );
- }
-
- /**
- * Get the file size in bytes
- *
- * @return int|false
- */
- public function getSize() {
- return filesize( $this->path );
- }
-
- /**
- * Get the file's last-modified timestamp
- *
- * @return string|false TS_MW timestamp or false on failure
- */
- public function getTimestamp() {
- wfSuppressWarnings();
- $timestamp = filemtime( $this->path );
- wfRestoreWarnings();
- if ( $timestamp !== false ) {
- $timestamp = wfTimestamp( TS_MW, $timestamp );
- }
- return $timestamp;
- }
-
- /**
- * Guess the MIME type from the file contents alone
- *
- * @return string
- */
- public function getMimeType() {
- return MimeMagic::singleton()->guessMimeType( $this->path, false );
- }
-
- /**
- * Get an associative array containing information about
- * a file with the given storage path.
- *
- * @param $ext Mixed: the file extension, or true to extract it from the filename.
- * Set it to false to ignore the extension.
- *
- * @return array
- */
- public function getProps( $ext = true ) {
- wfProfileIn( __METHOD__ );
- wfDebug( __METHOD__.": Getting file info for $this->path\n" );
-
- $info = self::placeholderProps();
- $info['fileExists'] = $this->exists();
-
- if ( $info['fileExists'] ) {
- $magic = MimeMagic::singleton();
-
- # get the file extension
- if ( $ext === true ) {
- $ext = self::extensionFromPath( $this->path );
- }
-
- # mime type according to file contents
- $info['file-mime'] = $this->getMimeType();
- # logical mime type
- $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
-
- list( $info['major_mime'], $info['minor_mime'] ) = File::splitMime( $info['mime'] );
- $info['media_type'] = $magic->getMediaType( $this->path, $info['mime'] );
-
- # Get size in bytes
- $info['size'] = $this->getSize();
-
- # Height, width and metadata
- $handler = MediaHandler::getHandler( $info['mime'] );
- if ( $handler ) {
- $tempImage = (object)array();
- $info['metadata'] = $handler->getMetadata( $tempImage, $this->path );
- $gis = $handler->getImageSize( $tempImage, $this->path, $info['metadata'] );
- if ( is_array( $gis ) ) {
- $info = $this->extractImageSizeInfo( $gis ) + $info;
- }
- }
- $info['sha1'] = $this->getSha1Base36();
-
- wfDebug(__METHOD__.": $this->path loaded, {$info['size']} bytes, {$info['mime']}.\n");
- } else {
- wfDebug(__METHOD__.": $this->path NOT FOUND!\n");
- }
-
- wfProfileOut( __METHOD__ );
- return $info;
- }
-
- /**
- * Placeholder file properties to use for files that don't exist
- *
- * @return Array
- */
- public static function placeholderProps() {
- $info = array();
- $info['fileExists'] = false;
- $info['mime'] = null;
- $info['media_type'] = MEDIATYPE_UNKNOWN;
- $info['metadata'] = '';
- $info['sha1'] = '';
- $info['width'] = 0;
- $info['height'] = 0;
- $info['bits'] = 0;
- return $info;
- }
-
- /**
- * Exract image size information
- *
- * @return Array
- */
- protected function extractImageSizeInfo( array $gis ) {
- $info = array();
- # NOTE: $gis[2] contains a code for the image type. This is no longer used.
- $info['width'] = $gis[0];
- $info['height'] = $gis[1];
- if ( isset( $gis['bits'] ) ) {
- $info['bits'] = $gis['bits'];
- } else {
- $info['bits'] = 0;
- }
- return $info;
- }
-
- /**
- * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
- * encoding, zero padded to 31 digits.
- *
- * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
- * fairly neatly.
- *
- * @return false|string False on failure
- */
- public function getSha1Base36() {
- wfProfileIn( __METHOD__ );
-
- wfSuppressWarnings();
- $hash = sha1_file( $this->path );
- wfRestoreWarnings();
- if ( $hash !== false ) {
- $hash = wfBaseConvert( $hash, 16, 36, 31 );
- }
-
- wfProfileOut( __METHOD__ );
- return $hash;
- }
-
- /**
- * Get the final file extension from a file system path
- *
- * @param $path string
- * @return string
- */
- public static function extensionFromPath( $path ) {
- $i = strrpos( $path, '.' );
- return strtolower( $i ? substr( $path, $i + 1 ) : '' );
- }
-
- /**
- * Get an associative array containing information about a file in the local filesystem.
- *
- * @param $path String: absolute local filesystem path
- * @param $ext Mixed: the file extension, or true to extract it from the filename.
- * Set it to false to ignore the extension.
- *
- * @return array
- */
- public static function getPropsFromPath( $path, $ext = true ) {
- $fsFile = new self( $path );
- return $fsFile->getProps( $ext );
- }
-
- /**
- * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
- * encoding, zero padded to 31 digits.
- *
- * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
- * fairly neatly.
- *
- * @param $path string
- *
- * @return false|string False on failure
- */
- public static function getSha1Base36FromPath( $path ) {
- $fsFile = new self( $path );
- return $fsFile->getSha1Base36();
- }
-}
diff --git a/includes/filerepo/backend/FSFileBackend.php b/includes/filerepo/backend/FSFileBackend.php
deleted file mode 100644
index 1a4c44ad..00000000
--- a/includes/filerepo/backend/FSFileBackend.php
+++ /dev/null
@@ -1,600 +0,0 @@
-<?php
-/**
- * @file
- * @ingroup FileBackend
- * @author Aaron Schulz
- */
-
-/**
- * Class for a file system (FS) based file backend.
- *
- * All "containers" each map to a directory under the backend's base directory.
- * For backwards-compatibility, some container paths can be set to custom paths.
- * The wiki ID will not be used in any custom paths, so this should be avoided.
- *
- * Having directories with thousands of files will diminish performance.
- * Sharding can be accomplished by using FileRepo-style hash paths.
- *
- * Status messages should avoid mentioning the internal FS paths.
- * PHP warnings are assumed to be logged rather than output.
- *
- * @ingroup FileBackend
- * @since 1.19
- */
-class FSFileBackend extends FileBackendStore {
- protected $basePath; // string; directory holding the container directories
- /** @var Array Map of container names to root paths */
- protected $containerPaths = array(); // for custom container paths
- protected $fileMode; // integer; file permission mode
-
- protected $hadWarningErrors = array();
-
- /**
- * @see FileBackendStore::__construct()
- * Additional $config params include:
- * basePath : File system directory that holds containers.
- * containerPaths : Map of container names to custom file system directories.
- * This should only be used for backwards-compatibility.
- * fileMode : Octal UNIX file permissions to use on files stored.
- */
- public function __construct( array $config ) {
- parent::__construct( $config );
-
- // Remove any possible trailing slash from directories
- if ( isset( $config['basePath'] ) ) {
- $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
- } else {
- $this->basePath = null; // none; containers must have explicit paths
- }
-
- if ( isset( $config['containerPaths'] ) ) {
- $this->containerPaths = (array)$config['containerPaths'];
- foreach ( $this->containerPaths as &$path ) {
- $path = rtrim( $path, '/' ); // remove trailing slash
- }
- }
-
- $this->fileMode = isset( $config['fileMode'] )
- ? $config['fileMode']
- : 0644;
- }
-
- /**
- * @see FileBackendStore::resolveContainerPath()
- */
- protected function resolveContainerPath( $container, $relStoragePath ) {
- // Check that container has a root directory
- if ( isset( $this->containerPaths[$container] ) || isset( $this->basePath ) ) {
- // Check for sane relative paths (assume the base paths are OK)
- if ( $this->isLegalRelPath( $relStoragePath ) ) {
- return $relStoragePath;
- }
- }
- return null;
- }
-
- /**
- * Sanity check a relative file system path for validity
- *
- * @param $path string Normalized relative path
- * @return bool
- */
- protected function isLegalRelPath( $path ) {
- // Check for file names longer than 255 chars
- if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
- return false;
- }
- if ( wfIsWindows() ) { // NTFS
- return !preg_match( '![:*?"<>|]!', $path );
- } else {
- return true;
- }
- }
-
- /**
- * Given the short (unresolved) and full (resolved) name of
- * a container, return the file system path of the container.
- *
- * @param $shortCont string
- * @param $fullCont string
- * @return string|null
- */
- protected function containerFSRoot( $shortCont, $fullCont ) {
- if ( isset( $this->containerPaths[$shortCont] ) ) {
- return $this->containerPaths[$shortCont];
- } elseif ( isset( $this->basePath ) ) {
- return "{$this->basePath}/{$fullCont}";
- }
- return null; // no container base path defined
- }
-
- /**
- * Get the absolute file system path for a storage path
- *
- * @param $storagePath string Storage path
- * @return string|null
- */
- protected function resolveToFSPath( $storagePath ) {
- list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
- if ( $relPath === null ) {
- return null; // invalid
- }
- list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $storagePath );
- $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
- if ( $relPath != '' ) {
- $fsPath .= "/{$relPath}";
- }
- return $fsPath;
- }
-
- /**
- * @see FileBackendStore::isPathUsableInternal()
- */
- public function isPathUsableInternal( $storagePath ) {
- $fsPath = $this->resolveToFSPath( $storagePath );
- if ( $fsPath === null ) {
- return false; // invalid
- }
- $parentDir = dirname( $fsPath );
-
- if ( file_exists( $fsPath ) ) {
- $ok = is_file( $fsPath ) && is_writable( $fsPath );
- } else {
- $ok = is_dir( $parentDir ) && is_writable( $parentDir );
- }
-
- return $ok;
- }
-
- /**
- * @see FileBackendStore::doStoreInternal()
- */
- protected function doStoreInternal( array $params ) {
- $status = Status::newGood();
-
- $dest = $this->resolveToFSPath( $params['dst'] );
- if ( $dest === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
- return $status;
- }
-
- if ( file_exists( $dest ) ) {
- if ( !empty( $params['overwrite'] ) ) {
- $ok = unlink( $dest );
- if ( !$ok ) {
- $status->fatal( 'backend-fail-delete', $params['dst'] );
- return $status;
- }
- } else {
- $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
- return $status;
- }
- }
-
- $ok = copy( $params['src'], $dest );
- if ( !$ok ) {
- $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
- return $status;
- }
-
- $this->chmod( $dest );
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doCopyInternal()
- */
- protected function doCopyInternal( array $params ) {
- $status = Status::newGood();
-
- $source = $this->resolveToFSPath( $params['src'] );
- if ( $source === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['src'] );
- return $status;
- }
-
- $dest = $this->resolveToFSPath( $params['dst'] );
- if ( $dest === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
- return $status;
- }
-
- if ( file_exists( $dest ) ) {
- if ( !empty( $params['overwrite'] ) ) {
- $ok = unlink( $dest );
- if ( !$ok ) {
- $status->fatal( 'backend-fail-delete', $params['dst'] );
- return $status;
- }
- } else {
- $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
- return $status;
- }
- }
-
- $ok = copy( $source, $dest );
- if ( !$ok ) {
- $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
- return $status;
- }
-
- $this->chmod( $dest );
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doMoveInternal()
- */
- protected function doMoveInternal( array $params ) {
- $status = Status::newGood();
-
- $source = $this->resolveToFSPath( $params['src'] );
- if ( $source === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['src'] );
- return $status;
- }
-
- $dest = $this->resolveToFSPath( $params['dst'] );
- if ( $dest === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
- return $status;
- }
-
- if ( file_exists( $dest ) ) {
- if ( !empty( $params['overwrite'] ) ) {
- // Windows does not support moving over existing files
- if ( wfIsWindows() ) {
- $ok = unlink( $dest );
- if ( !$ok ) {
- $status->fatal( 'backend-fail-delete', $params['dst'] );
- return $status;
- }
- }
- } else {
- $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
- return $status;
- }
- }
-
- $ok = rename( $source, $dest );
- clearstatcache(); // file no longer at source
- if ( !$ok ) {
- $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
- return $status;
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doDeleteInternal()
- */
- protected function doDeleteInternal( array $params ) {
- $status = Status::newGood();
-
- $source = $this->resolveToFSPath( $params['src'] );
- if ( $source === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['src'] );
- return $status;
- }
-
- if ( !is_file( $source ) ) {
- if ( empty( $params['ignoreMissingSource'] ) ) {
- $status->fatal( 'backend-fail-delete', $params['src'] );
- }
- return $status; // do nothing; either OK or bad status
- }
-
- $ok = unlink( $source );
- if ( !$ok ) {
- $status->fatal( 'backend-fail-delete', $params['src'] );
- return $status;
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doCreateInternal()
- */
- protected function doCreateInternal( array $params ) {
- $status = Status::newGood();
-
- $dest = $this->resolveToFSPath( $params['dst'] );
- if ( $dest === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
- return $status;
- }
-
- if ( file_exists( $dest ) ) {
- if ( !empty( $params['overwrite'] ) ) {
- $ok = unlink( $dest );
- if ( !$ok ) {
- $status->fatal( 'backend-fail-delete', $params['dst'] );
- return $status;
- }
- } else {
- $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
- return $status;
- }
- }
-
- $bytes = file_put_contents( $dest, $params['content'] );
- if ( $bytes === false ) {
- $status->fatal( 'backend-fail-create', $params['dst'] );
- return $status;
- }
-
- $this->chmod( $dest );
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doPrepareInternal()
- */
- protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
- $status = Status::newGood();
- list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
- $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
- $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
- if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
- $status->fatal( 'directorycreateerror', $params['dir'] );
- } elseif ( !is_writable( $dir ) ) {
- $status->fatal( 'directoryreadonlyerror', $params['dir'] );
- } elseif ( !is_readable( $dir ) ) {
- $status->fatal( 'directorynotreadableerror', $params['dir'] );
- }
- return $status;
- }
-
- /**
- * @see FileBackendStore::doSecureInternal()
- */
- protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
- $status = Status::newGood();
- list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
- $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
- $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
- // Seed new directories with a blank index.html, to prevent crawling...
- if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
- $bytes = file_put_contents( "{$dir}/index.html", '' );
- if ( !$bytes ) {
- $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
- return $status;
- }
- }
- // Add a .htaccess file to the root of the container...
- if ( !empty( $params['noAccess'] ) ) {
- if ( !file_exists( "{$contRoot}/.htaccess" ) ) {
- $bytes = file_put_contents( "{$contRoot}/.htaccess", "Deny from all\n" );
- if ( !$bytes ) {
- $storeDir = "mwstore://{$this->name}/{$shortCont}";
- $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
- return $status;
- }
- }
- }
- return $status;
- }
-
- /**
- * @see FileBackendStore::doCleanInternal()
- */
- protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
- $status = Status::newGood();
- list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
- $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
- $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
- wfSuppressWarnings();
- if ( is_dir( $dir ) ) {
- rmdir( $dir ); // remove directory if empty
- }
- wfRestoreWarnings();
- return $status;
- }
-
- /**
- * @see FileBackendStore::doFileExists()
- */
- protected function doGetFileStat( array $params ) {
- $source = $this->resolveToFSPath( $params['src'] );
- if ( $source === null ) {
- return false; // invalid storage path
- }
-
- $this->trapWarnings(); // don't trust 'false' if there were errors
- $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
- $hadError = $this->untrapWarnings();
-
- if ( $stat ) {
- return array(
- 'mtime' => wfTimestamp( TS_MW, $stat['mtime'] ),
- 'size' => $stat['size']
- );
- } elseif ( !$hadError ) {
- return false; // file does not exist
- } else {
- return null; // failure
- }
- }
-
- /**
- * @see FileBackendStore::doClearCache()
- */
- protected function doClearCache( array $paths = null ) {
- clearstatcache(); // clear the PHP file stat cache
- }
-
- /**
- * @see FileBackendStore::getFileListInternal()
- */
- public function getFileListInternal( $fullCont, $dirRel, array $params ) {
- list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
- $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
- $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
- $exists = is_dir( $dir );
- if ( !$exists ) {
- wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
- return array(); // nothing under this dir
- }
- $readable = is_readable( $dir );
- if ( !$readable ) {
- wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
- return null; // bad permissions?
- }
- return new FSFileBackendFileList( $dir );
- }
-
- /**
- * @see FileBackendStore::getLocalReference()
- */
- public function getLocalReference( array $params ) {
- $source = $this->resolveToFSPath( $params['src'] );
- if ( $source === null ) {
- return null;
- }
- return new FSFile( $source );
- }
-
- /**
- * @see FileBackendStore::getLocalCopy()
- */
- public function getLocalCopy( array $params ) {
- $source = $this->resolveToFSPath( $params['src'] );
- if ( $source === null ) {
- return null;
- }
-
- // Create a new temporary file with the same extension...
- $ext = FileBackend::extensionFromPath( $params['src'] );
- $tmpFile = TempFSFile::factory( wfBaseName( $source ) . '_', $ext );
- if ( !$tmpFile ) {
- return null;
- }
- $tmpPath = $tmpFile->getPath();
-
- // Copy the source file over the temp file
- $ok = copy( $source, $tmpPath );
- if ( !$ok ) {
- return null;
- }
-
- $this->chmod( $tmpPath );
-
- return $tmpFile;
- }
-
- /**
- * Chmod a file, suppressing the warnings
- *
- * @param $path string Absolute file system path
- * @return bool Success
- */
- protected function chmod( $path ) {
- wfSuppressWarnings();
- $ok = chmod( $path, $this->fileMode );
- wfRestoreWarnings();
-
- return $ok;
- }
-
- /**
- * Listen for E_WARNING errors and track whether any happen
- *
- * @return bool
- */
- protected function trapWarnings() {
- $this->hadWarningErrors[] = false; // push to stack
- set_error_handler( array( $this, 'handleWarning' ), E_WARNING );
- return false; // invoke normal PHP error handler
- }
-
- /**
- * Stop listening for E_WARNING errors and return true if any happened
- *
- * @return bool
- */
- protected function untrapWarnings() {
- restore_error_handler(); // restore previous handler
- return array_pop( $this->hadWarningErrors ); // pop from stack
- }
-
- private function handleWarning() {
- $this->hadWarningErrors[count( $this->hadWarningErrors ) - 1] = true;
- return true; // suppress from PHP handler
- }
-}
-
-/**
- * Wrapper around RecursiveDirectoryIterator that catches
- * exception or does any custom behavoir that we may want.
- * Do not use this class from places outside FSFileBackend.
- *
- * @ingroup FileBackend
- */
-class FSFileBackendFileList implements Iterator {
- /** @var RecursiveIteratorIterator */
- protected $iter;
- protected $suffixStart; // integer
- protected $pos = 0; // integer
-
- /**
- * @param $dir string file system directory
- */
- public function __construct( $dir ) {
- $dir = realpath( $dir ); // normalize
- $this->suffixStart = strlen( $dir ) + 1; // size of "path/to/dir/"
- try {
- # Get an iterator that will return leaf nodes (non-directories)
- if ( MWInit::classExists( 'FilesystemIterator' ) ) { // PHP >= 5.3
- # RecursiveDirectoryIterator extends FilesystemIterator.
- # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
- $flags = FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS;
- $this->iter = new RecursiveIteratorIterator(
- new RecursiveDirectoryIterator( $dir, $flags ) );
- } else { // PHP < 5.3
- # RecursiveDirectoryIterator extends DirectoryIterator
- $this->iter = new RecursiveIteratorIterator(
- new RecursiveDirectoryIterator( $dir ) );
- }
- } catch ( UnexpectedValueException $e ) {
- $this->iter = null; // bad permissions? deleted?
- }
- }
-
- public function current() {
- // Return only the relative path and normalize slashes to FileBackend-style
- // Make sure to use the realpath since the suffix is based upon that
- return str_replace( '\\', '/',
- substr( realpath( $this->iter->current() ), $this->suffixStart ) );
- }
-
- public function key() {
- return $this->pos;
- }
-
- public function next() {
- try {
- $this->iter->next();
- } catch ( UnexpectedValueException $e ) {
- $this->iter = null;
- }
- ++$this->pos;
- }
-
- public function rewind() {
- $this->pos = 0;
- try {
- $this->iter->rewind();
- } catch ( UnexpectedValueException $e ) {
- $this->iter = null;
- }
- }
-
- public function valid() {
- return $this->iter && $this->iter->valid();
- }
-}
diff --git a/includes/filerepo/backend/FileBackend.php b/includes/filerepo/backend/FileBackend.php
deleted file mode 100644
index 9433bcb4..00000000
--- a/includes/filerepo/backend/FileBackend.php
+++ /dev/null
@@ -1,1739 +0,0 @@
-<?php
-/**
- * @defgroup FileBackend File backend
- * @ingroup FileRepo
- *
- * This module regroup classes meant for MediaWiki to interacts with
- */
-
-/**
- * @file
- * @ingroup FileBackend
- * @author Aaron Schulz
- */
-
-/**
- * Base class for all file backend classes (including multi-write backends).
- *
- * This class defines the methods as abstract that subclasses must implement.
- * Outside callers can assume that all backends will have these functions.
- *
- * All "storage paths" are of the format "mwstore://backend/container/path".
- * The paths use UNIX file system (FS) notation, though any particular backend may
- * not actually be using a local filesystem. Therefore, the paths are only virtual.
- *
- * Backend contents are stored under wiki-specific container names by default.
- * For legacy reasons, this has no effect for the FS backend class, and per-wiki
- * segregation must be done by setting the container paths appropriately.
- *
- * FS-based backends are somewhat more restrictive due to the existence of real
- * directory files; a regular file cannot have the same name as a directory. Other
- * backends with virtual directories may not have this limitation. Callers should
- * store files in such a way that no files and directories are under the same path.
- *
- * Methods should avoid throwing exceptions at all costs.
- * As a corollary, external dependencies should be kept to a minimum.
- *
- * @ingroup FileBackend
- * @since 1.19
- */
-abstract class FileBackend {
- protected $name; // string; unique backend name
- protected $wikiId; // string; unique wiki name
- protected $readOnly; // string; read-only explanation message
- /** @var LockManager */
- protected $lockManager;
-
- /**
- * Create a new backend instance from configuration.
- * This should only be called from within FileBackendGroup.
- *
- * $config includes:
- * 'name' : The unique name of this backend.
- * This should consist of alphanumberic, '-', and '_' characters.
- * This name should not be changed after use.
- * 'wikiId' : Prefix to container names that is unique to this wiki.
- * This should consist of alphanumberic, '-', and '_' characters.
- * 'lockManager' : Registered name of a file lock manager to use.
- * 'readOnly' : Write operations are disallowed if this is a non-empty string.
- * It should be an explanation for the backend being read-only.
- *
- * @param $config Array
- */
- public function __construct( array $config ) {
- $this->name = $config['name'];
- if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
- throw new MWException( "Backend name `{$this->name}` is invalid." );
- }
- $this->wikiId = isset( $config['wikiId'] )
- ? $config['wikiId']
- : wfWikiID(); // e.g. "my_wiki-en_"
- $this->lockManager = ( $config['lockManager'] instanceof LockManager )
- ? $config['lockManager']
- : LockManagerGroup::singleton()->get( $config['lockManager'] );
- $this->readOnly = isset( $config['readOnly'] )
- ? (string)$config['readOnly']
- : '';
- }
-
- /**
- * Get the unique backend name.
- * We may have multiple different backends of the same type.
- * For example, we can have two Swift backends using different proxies.
- *
- * @return string
- */
- final public function getName() {
- return $this->name;
- }
-
- /**
- * Check if this backend is read-only
- *
- * @return bool
- */
- final public function isReadOnly() {
- return ( $this->readOnly != '' );
- }
-
- /**
- * Get an explanatory message if this backend is read-only
- *
- * @return string|false Returns falls if the backend is not read-only
- */
- final public function getReadOnlyReason() {
- return ( $this->readOnly != '' ) ? $this->readOnly : false;
- }
-
- /**
- * This is the main entry point into the backend for write operations.
- * Callers supply an ordered list of operations to perform as a transaction.
- * Files will be locked, the stat cache cleared, and then the operations attempted.
- * If any serious errors occur, all attempted operations will be rolled back.
- *
- * $ops is an array of arrays. The outer array holds a list of operations.
- * Each inner array is a set of key value pairs that specify an operation.
- *
- * Supported operations and their parameters:
- * a) Create a new file in storage with the contents of a string
- * array(
- * 'op' => 'create',
- * 'dst' => <storage path>,
- * 'content' => <string of new file contents>,
- * 'overwrite' => <boolean>,
- * 'overwriteSame' => <boolean>
- * )
- * b) Copy a file system file into storage
- * array(
- * 'op' => 'store',
- * 'src' => <file system path>,
- * 'dst' => <storage path>,
- * 'overwrite' => <boolean>,
- * 'overwriteSame' => <boolean>
- * )
- * c) Copy a file within storage
- * array(
- * 'op' => 'copy',
- * 'src' => <storage path>,
- * 'dst' => <storage path>,
- * 'overwrite' => <boolean>,
- * 'overwriteSame' => <boolean>
- * )
- * d) Move a file within storage
- * array(
- * 'op' => 'move',
- * 'src' => <storage path>,
- * 'dst' => <storage path>,
- * 'overwrite' => <boolean>,
- * 'overwriteSame' => <boolean>
- * )
- * e) Delete a file within storage
- * array(
- * 'op' => 'delete',
- * 'src' => <storage path>,
- * 'ignoreMissingSource' => <boolean>
- * )
- * f) Do nothing (no-op)
- * array(
- * 'op' => 'null',
- * )
- *
- * Boolean flags for operations (operation-specific):
- * 'ignoreMissingSource' : The operation will simply succeed and do
- * nothing if the source file does not exist.
- * 'overwrite' : Any destination file will be overwritten.
- * 'overwriteSame' : An error will not be given if a file already
- * exists at the destination that has the same
- * contents as the new contents to be written there.
- *
- * $opts is an associative of boolean flags, including:
- * 'force' : Errors that would normally cause a rollback do not.
- * The remaining operations are still attempted if any fail.
- * 'nonLocking' : No locks are acquired for the operations.
- * This can increase performance for non-critical writes.
- * This has no effect unless the 'force' flag is set.
- * 'allowStale' : Don't require the latest available data.
- * This can increase performance for non-critical writes.
- * This has no effect unless the 'force' flag is set.
- *
- * Remarks on locking:
- * File system paths given to operations should refer to files that are
- * already locked or otherwise safe from modification from other processes.
- * Normally these files will be new temp files, which should be adequate.
- *
- * Return value:
- * This returns a Status, which contains all warnings and fatals that occured
- * during the operation. The 'failCount', 'successCount', and 'success' members
- * will reflect each operation attempted. The status will be "OK" unless:
- * a) unexpected operation errors occurred (network partitions, disk full...)
- * b) significant operation errors occured and 'force' was not set
- *
- * @param $ops Array List of operations to execute in order
- * @param $opts Array Batch operation options
- * @return Status
- */
- final public function doOperations( array $ops, array $opts = array() ) {
- if ( $this->isReadOnly() ) {
- return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- if ( empty( $opts['force'] ) ) { // sanity
- unset( $opts['nonLocking'] );
- unset( $opts['allowStale'] );
- }
- return $this->doOperationsInternal( $ops, $opts );
- }
-
- /**
- * @see FileBackend::doOperations()
- */
- abstract protected function doOperationsInternal( array $ops, array $opts );
-
- /**
- * Same as doOperations() except it takes a single operation.
- * If you are doing a batch of operations that should either
- * all succeed or all fail, then use that function instead.
- *
- * @see FileBackend::doOperations()
- *
- * @param $op Array Operation
- * @param $opts Array Operation options
- * @return Status
- */
- final public function doOperation( array $op, array $opts = array() ) {
- return $this->doOperations( array( $op ), $opts );
- }
-
- /**
- * Performs a single create operation.
- * This sets $params['op'] to 'create' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param $params Array Operation parameters
- * @param $opts Array Operation options
- * @return Status
- */
- final public function create( array $params, array $opts = array() ) {
- $params['op'] = 'create';
- return $this->doOperation( $params, $opts );
- }
-
- /**
- * Performs a single store operation.
- * This sets $params['op'] to 'store' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param $params Array Operation parameters
- * @param $opts Array Operation options
- * @return Status
- */
- final public function store( array $params, array $opts = array() ) {
- $params['op'] = 'store';
- return $this->doOperation( $params, $opts );
- }
-
- /**
- * Performs a single copy operation.
- * This sets $params['op'] to 'copy' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param $params Array Operation parameters
- * @param $opts Array Operation options
- * @return Status
- */
- final public function copy( array $params, array $opts = array() ) {
- $params['op'] = 'copy';
- return $this->doOperation( $params, $opts );
- }
-
- /**
- * Performs a single move operation.
- * This sets $params['op'] to 'move' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param $params Array Operation parameters
- * @param $opts Array Operation options
- * @return Status
- */
- final public function move( array $params, array $opts = array() ) {
- $params['op'] = 'move';
- return $this->doOperation( $params, $opts );
- }
-
- /**
- * Performs a single delete operation.
- * This sets $params['op'] to 'delete' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param $params Array Operation parameters
- * @param $opts Array Operation options
- * @return Status
- */
- final public function delete( array $params, array $opts = array() ) {
- $params['op'] = 'delete';
- return $this->doOperation( $params, $opts );
- }
-
- /**
- * Concatenate a list of storage files into a single file system file.
- * The target path should refer to a file that is already locked or
- * otherwise safe from modification from other processes. Normally,
- * the file will be a new temp file, which should be adequate.
- * $params include:
- * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
- * dst : file system path to 0-byte temp file
- *
- * @param $params Array Operation parameters
- * @return Status
- */
- abstract public function concatenate( array $params );
-
- /**
- * Prepare a storage directory for usage.
- * This will create any required containers and parent directories.
- * Backends using key/value stores only need to create the container.
- *
- * $params include:
- * dir : storage directory
- *
- * @param $params Array
- * @return Status
- */
- final public function prepare( array $params ) {
- if ( $this->isReadOnly() ) {
- return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- return $this->doPrepare( $params );
- }
-
- /**
- * @see FileBackend::prepare()
- */
- abstract protected function doPrepare( array $params );
-
- /**
- * Take measures to block web access to a storage directory and
- * the container it belongs to. FS backends might add .htaccess
- * files whereas key/value store backends might restrict container
- * access to the auth user that represents end-users in web request.
- * This is not guaranteed to actually do anything.
- *
- * $params include:
- * dir : storage directory
- * noAccess : try to deny file access
- * noListing : try to deny file listing
- *
- * @param $params Array
- * @return Status
- */
- final public function secure( array $params ) {
- if ( $this->isReadOnly() ) {
- return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- $status = $this->doPrepare( $params ); // dir must exist to restrict it
- if ( $status->isOK() ) {
- $status->merge( $this->doSecure( $params ) );
- }
- return $status;
- }
-
- /**
- * @see FileBackend::secure()
- */
- abstract protected function doSecure( array $params );
-
- /**
- * Delete a storage directory if it is empty.
- * Backends using key/value stores may do nothing unless the directory
- * is that of an empty container, in which case it should be deleted.
- *
- * $params include:
- * dir : storage directory
- *
- * @param $params Array
- * @return Status
- */
- final public function clean( array $params ) {
- if ( $this->isReadOnly() ) {
- return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- return $this->doClean( $params );
- }
-
- /**
- * @see FileBackend::clean()
- */
- abstract protected function doClean( array $params );
-
- /**
- * Check if a file exists at a storage path in the backend.
- * This returns false if only a directory exists at the path.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return bool|null Returns null on failure
- */
- abstract public function fileExists( array $params );
-
- /**
- * Get the last-modified timestamp of the file at a storage path.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return string|false TS_MW timestamp or false on failure
- */
- abstract public function getFileTimestamp( array $params );
-
- /**
- * Get the contents of a file at a storage path in the backend.
- * This should be avoided for potentially large files.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return string|false Returns false on failure
- */
- abstract public function getFileContents( array $params );
-
- /**
- * Get the size (bytes) of a file at a storage path in the backend.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return integer|false Returns false on failure
- */
- abstract public function getFileSize( array $params );
-
- /**
- * Get quick information about a file at a storage path in the backend.
- * If the file does not exist, then this returns false.
- * Otherwise, the result is an associative array that includes:
- * mtime : the last-modified timestamp (TS_MW)
- * size : the file size (bytes)
- * Additional values may be included for internal use only.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return Array|false|null Returns null on failure
- */
- abstract public function getFileStat( array $params );
-
- /**
- * Get a SHA-1 hash of the file at a storage path in the backend.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return string|false Hash string or false on failure
- */
- abstract public function getFileSha1Base36( array $params );
-
- /**
- * Get the properties of the file at a storage path in the backend.
- * Returns FSFile::placeholderProps() on failure.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return Array
- */
- abstract public function getFileProps( array $params );
-
- /**
- * Stream the file at a storage path in the backend.
- * If the file does not exists, a 404 error will be given.
- * Appropriate HTTP headers (Status, Content-Type, Content-Length)
- * must be sent if streaming began, while none should be sent otherwise.
- * Implementations should flush the output buffer before sending data.
- *
- * $params include:
- * src : source storage path
- * headers : additional HTTP headers to send on success
- * latest : use the latest available data
- *
- * @param $params Array
- * @return Status
- */
- abstract public function streamFile( array $params );
-
- /**
- * Returns a file system file, identical to the file at a storage path.
- * The file returned is either:
- * a) A local copy of the file at a storage path in the backend.
- * The temporary copy will have the same extension as the source.
- * b) An original of the file at a storage path in the backend.
- * Temporary files may be purged when the file object falls out of scope.
- *
- * Write operations should *never* be done on this file as some backends
- * may do internal tracking or may be instances of FileBackendMultiWrite.
- * In that later case, there are copies of the file that must stay in sync.
- * Additionally, further calls to this function may return the same file.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return FSFile|null Returns null on failure
- */
- abstract public function getLocalReference( array $params );
-
- /**
- * Get a local copy on disk of the file at a storage path in the backend.
- * The temporary copy will have the same file extension as the source.
- * Temporary files may be purged when the file object falls out of scope.
- *
- * $params include:
- * src : source storage path
- * latest : use the latest available data
- *
- * @param $params Array
- * @return TempFSFile|null Returns null on failure
- */
- abstract public function getLocalCopy( array $params );
-
- /**
- * Get an iterator to list out all stored files under a storage directory.
- * If the directory is of the form "mwstore://backend/container",
- * then all files in the container should be listed.
- * If the directory is of form "mwstore://backend/container/dir",
- * then all files under that container directory should be listed.
- * Results should be storage paths relative to the given directory.
- *
- * Storage backends with eventual consistency might return stale data.
- *
- * $params include:
- * dir : storage path directory
- *
- * @return Traversable|Array|null Returns null on failure
- */
- abstract public function getFileList( array $params );
-
- /**
- * Invalidate any in-process file existence and property cache.
- * If $paths is given, then only the cache for those files will be cleared.
- *
- * @param $paths Array Storage paths (optional)
- * @return void
- */
- public function clearCache( array $paths = null ) {}
-
- /**
- * Lock the files at the given storage paths in the backend.
- * This will either lock all the files or none (on failure).
- *
- * Callers should consider using getScopedFileLocks() instead.
- *
- * @param $paths Array Storage paths
- * @param $type integer LockManager::LOCK_* constant
- * @return Status
- */
- final public function lockFiles( array $paths, $type ) {
- return $this->lockManager->lock( $paths, $type );
- }
-
- /**
- * Unlock the files at the given storage paths in the backend.
- *
- * @param $paths Array Storage paths
- * @param $type integer LockManager::LOCK_* constant
- * @return Status
- */
- final public function unlockFiles( array $paths, $type ) {
- return $this->lockManager->unlock( $paths, $type );
- }
-
- /**
- * Lock the files at the given storage paths in the backend.
- * This will either lock all the files or none (on failure).
- * On failure, the status object will be updated with errors.
- *
- * Once the return value goes out scope, the locks will be released and
- * the status updated. Unlock fatals will not change the status "OK" value.
- *
- * @param $paths Array Storage paths
- * @param $type integer LockManager::LOCK_* constant
- * @param $status Status Status to update on lock/unlock
- * @return ScopedLock|null Returns null on failure
- */
- final public function getScopedFileLocks( array $paths, $type, Status $status ) {
- return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
- }
-
- /**
- * Check if a given path is a "mwstore://" path.
- * This does not do any further validation or any existence checks.
- *
- * @param $path string
- * @return bool
- */
- final public static function isStoragePath( $path ) {
- return ( strpos( $path, 'mwstore://' ) === 0 );
- }
-
- /**
- * Split a storage path into a backend name, a container name,
- * and a relative file path. The relative path may be the empty string.
- * This does not do any path normalization or traversal checks.
- *
- * @param $storagePath string
- * @return Array (backend, container, rel object) or (null, null, null)
- */
- final public static function splitStoragePath( $storagePath ) {
- if ( self::isStoragePath( $storagePath ) ) {
- // Remove the "mwstore://" prefix and split the path
- $parts = explode( '/', substr( $storagePath, 10 ), 3 );
- if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
- if ( count( $parts ) == 3 ) {
- return $parts; // e.g. "backend/container/path"
- } else {
- return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
- }
- }
- }
- return array( null, null, null );
- }
-
- /**
- * Normalize a storage path by cleaning up directory separators.
- * Returns null if the path is not of the format of a valid storage path.
- *
- * @param $storagePath string
- * @return string|null
- */
- final public static function normalizeStoragePath( $storagePath ) {
- list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
- if ( $relPath !== null ) { // must be for this backend
- $relPath = self::normalizeContainerPath( $relPath );
- if ( $relPath !== null ) {
- return ( $relPath != '' )
- ? "mwstore://{$backend}/{$container}/{$relPath}"
- : "mwstore://{$backend}/{$container}";
- }
- }
- return null;
- }
-
- /**
- * Validate and normalize a relative storage path.
- * Null is returned if the path involves directory traversal.
- * Traversal is insecure for FS backends and broken for others.
- *
- * @param $path string Storage path relative to a container
- * @return string|null
- */
- final protected static function normalizeContainerPath( $path ) {
- // Normalize directory separators
- $path = strtr( $path, '\\', '/' );
- // Collapse any consecutive directory separators
- $path = preg_replace( '![/]{2,}!', '/', $path );
- // Remove any leading directory separator
- $path = ltrim( $path, '/' );
- // Use the same traversal protection as Title::secureAndSplit()
- if ( strpos( $path, '.' ) !== false ) {
- if (
- $path === '.' ||
- $path === '..' ||
- strpos( $path, './' ) === 0 ||
- strpos( $path, '../' ) === 0 ||
- strpos( $path, '/./' ) !== false ||
- strpos( $path, '/../' ) !== false
- ) {
- return null;
- }
- }
- return $path;
- }
-
- /**
- * Get the parent storage directory of a storage path.
- * This returns a path like "mwstore://backend/container",
- * "mwstore://backend/container/...", or null if there is no parent.
- *
- * @param $storagePath string
- * @return string|null
- */
- final public static function parentStoragePath( $storagePath ) {
- $storagePath = dirname( $storagePath );
- list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
- return ( $rel === null ) ? null : $storagePath;
- }
-
- /**
- * Get the final extension from a storage or FS path
- *
- * @param $path string
- * @return string
- */
- final public static function extensionFromPath( $path ) {
- $i = strrpos( $path, '.' );
- return strtolower( $i ? substr( $path, $i + 1 ) : '' );
- }
-}
-
-/**
- * @brief Base class for all backends associated with a particular storage medium.
- *
- * This class defines the methods as abstract that subclasses must implement.
- * Outside callers should *not* use functions with "Internal" in the name.
- *
- * The FileBackend operations are implemented using basic functions
- * such as storeInternal(), copyInternal(), deleteInternal() and the like.
- * This class is also responsible for path resolution and sanitization.
- *
- * @ingroup FileBackend
- * @since 1.19
- */
-abstract class FileBackendStore extends FileBackend {
- /** @var Array Map of paths to small (RAM/disk) cache items */
- protected $cache = array(); // (storage path => key => value)
- protected $maxCacheSize = 100; // integer; max paths with entries
- /** @var Array Map of paths to large (RAM/disk) cache items */
- protected $expensiveCache = array(); // (storage path => key => value)
- protected $maxExpensiveCacheSize = 10; // integer; max paths with entries
-
- /** @var Array Map of container names to sharding settings */
- protected $shardViaHashLevels = array(); // (container name => config array)
-
- protected $maxFileSize = 1000000000; // integer bytes (1GB)
-
- /**
- * Get the maximum allowable file size given backend
- * medium restrictions and basic performance constraints.
- * Do not call this function from places outside FileBackend and FileOp.
- *
- * @return integer Bytes
- */
- final public function maxFileSizeInternal() {
- return $this->maxFileSize;
- }
-
- /**
- * Check if a file can be created at a given storage path.
- * FS backends should check if the parent directory exists and the file is writable.
- * Backends using key/value stores should check if the container exists.
- *
- * @param $storagePath string
- * @return bool
- */
- abstract public function isPathUsableInternal( $storagePath );
-
- /**
- * Create a file in the backend with the given contents.
- * Do not call this function from places outside FileBackend and FileOp.
- *
- * $params include:
- * content : the raw file contents
- * dst : destination storage path
- * overwrite : overwrite any file that exists at the destination
- *
- * @param $params Array
- * @return Status
- */
- final public function createInternal( array $params ) {
- wfProfileIn( __METHOD__ );
- if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
- $status = Status::newFatal( 'backend-fail-create', $params['dst'] );
- } else {
- $status = $this->doCreateInternal( $params );
- $this->clearCache( array( $params['dst'] ) );
- }
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::createInternal()
- */
- abstract protected function doCreateInternal( array $params );
-
- /**
- * Store a file into the backend from a file on disk.
- * Do not call this function from places outside FileBackend and FileOp.
- *
- * $params include:
- * src : source path on disk
- * dst : destination storage path
- * overwrite : overwrite any file that exists at the destination
- *
- * @param $params Array
- * @return Status
- */
- final public function storeInternal( array $params ) {
- wfProfileIn( __METHOD__ );
- if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
- $status = Status::newFatal( 'backend-fail-store', $params['dst'] );
- } else {
- $status = $this->doStoreInternal( $params );
- $this->clearCache( array( $params['dst'] ) );
- }
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::storeInternal()
- */
- abstract protected function doStoreInternal( array $params );
-
- /**
- * Copy a file from one storage path to another in the backend.
- * Do not call this function from places outside FileBackend and FileOp.
- *
- * $params include:
- * src : source storage path
- * dst : destination storage path
- * overwrite : overwrite any file that exists at the destination
- *
- * @param $params Array
- * @return Status
- */
- final public function copyInternal( array $params ) {
- wfProfileIn( __METHOD__ );
- $status = $this->doCopyInternal( $params );
- $this->clearCache( array( $params['dst'] ) );
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::copyInternal()
- */
- abstract protected function doCopyInternal( array $params );
-
- /**
- * Delete a file at the storage path.
- * Do not call this function from places outside FileBackend and FileOp.
- *
- * $params include:
- * src : source storage path
- * ignoreMissingSource : do nothing if the source file does not exist
- *
- * @param $params Array
- * @return Status
- */
- final public function deleteInternal( array $params ) {
- wfProfileIn( __METHOD__ );
- $status = $this->doDeleteInternal( $params );
- $this->clearCache( array( $params['src'] ) );
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::deleteInternal()
- */
- abstract protected function doDeleteInternal( array $params );
-
- /**
- * Move a file from one storage path to another in the backend.
- * Do not call this function from places outside FileBackend and FileOp.
- *
- * $params include:
- * src : source storage path
- * dst : destination storage path
- * overwrite : overwrite any file that exists at the destination
- *
- * @param $params Array
- * @return Status
- */
- final public function moveInternal( array $params ) {
- wfProfileIn( __METHOD__ );
- $status = $this->doMoveInternal( $params );
- $this->clearCache( array( $params['src'], $params['dst'] ) );
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::moveInternal()
- */
- protected function doMoveInternal( array $params ) {
- // Copy source to dest
- $status = $this->copyInternal( $params );
- if ( $status->isOK() ) {
- // Delete source (only fails due to races or medium going down)
- $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
- $status->setResult( true, $status->value ); // ignore delete() errors
- }
- return $status;
- }
-
- /**
- * @see FileBackend::concatenate()
- */
- final public function concatenate( array $params ) {
- wfProfileIn( __METHOD__ );
- $status = Status::newGood();
-
- // Try to lock the source files for the scope of this function
- $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
- if ( $status->isOK() ) {
- // Actually do the concatenation
- $status->merge( $this->doConcatenate( $params ) );
- }
-
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::concatenate()
- */
- protected function doConcatenate( array $params ) {
- $status = Status::newGood();
- $tmpPath = $params['dst']; // convenience
-
- // Check that the specified temp file is valid...
- wfSuppressWarnings();
- $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
- wfRestoreWarnings();
- if ( !$ok ) { // not present or not empty
- $status->fatal( 'backend-fail-opentemp', $tmpPath );
- return $status;
- }
-
- // Build up the temp file using the source chunks (in order)...
- $tmpHandle = fopen( $tmpPath, 'ab' );
- if ( $tmpHandle === false ) {
- $status->fatal( 'backend-fail-opentemp', $tmpPath );
- return $status;
- }
- foreach ( $params['srcs'] as $virtualSource ) {
- // Get a local FS version of the chunk
- $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
- if ( !$tmpFile ) {
- $status->fatal( 'backend-fail-read', $virtualSource );
- return $status;
- }
- // Get a handle to the local FS version
- $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
- if ( $sourceHandle === false ) {
- fclose( $tmpHandle );
- $status->fatal( 'backend-fail-read', $virtualSource );
- return $status;
- }
- // Append chunk to file (pass chunk size to avoid magic quotes)
- if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
- fclose( $sourceHandle );
- fclose( $tmpHandle );
- $status->fatal( 'backend-fail-writetemp', $tmpPath );
- return $status;
- }
- fclose( $sourceHandle );
- }
- if ( !fclose( $tmpHandle ) ) {
- $status->fatal( 'backend-fail-closetemp', $tmpPath );
- return $status;
- }
-
- clearstatcache(); // temp file changed
-
- return $status;
- }
-
- /**
- * @see FileBackend::doPrepare()
- */
- final protected function doPrepare( array $params ) {
- wfProfileIn( __METHOD__ );
-
- $status = Status::newGood();
- list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
- if ( $dir === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
- wfProfileOut( __METHOD__ );
- return $status; // invalid storage path
- }
-
- if ( $shard !== null ) { // confined to a single container/shard
- $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
- } else { // directory is on several shards
- wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
- list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
- foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
- $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
- }
- }
-
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::doPrepare()
- */
- protected function doPrepareInternal( $container, $dir, array $params ) {
- return Status::newGood();
- }
-
- /**
- * @see FileBackend::doSecure()
- */
- final protected function doSecure( array $params ) {
- wfProfileIn( __METHOD__ );
- $status = Status::newGood();
-
- list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
- if ( $dir === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
- wfProfileOut( __METHOD__ );
- return $status; // invalid storage path
- }
-
- if ( $shard !== null ) { // confined to a single container/shard
- $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
- } else { // directory is on several shards
- wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
- list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
- foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
- $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
- }
- }
-
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::doSecure()
- */
- protected function doSecureInternal( $container, $dir, array $params ) {
- return Status::newGood();
- }
-
- /**
- * @see FileBackend::doClean()
- */
- final protected function doClean( array $params ) {
- wfProfileIn( __METHOD__ );
- $status = Status::newGood();
-
- list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
- if ( $dir === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
- wfProfileOut( __METHOD__ );
- return $status; // invalid storage path
- }
-
- // Attempt to lock this directory...
- $filesLockEx = array( $params['dir'] );
- $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
- if ( !$status->isOK() ) {
- wfProfileOut( __METHOD__ );
- return $status; // abort
- }
-
- if ( $shard !== null ) { // confined to a single container/shard
- $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
- } else { // directory is on several shards
- wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
- list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
- foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
- $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
- }
- }
-
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::doClean()
- */
- protected function doCleanInternal( $container, $dir, array $params ) {
- return Status::newGood();
- }
-
- /**
- * @see FileBackend::fileExists()
- */
- final public function fileExists( array $params ) {
- wfProfileIn( __METHOD__ );
- $stat = $this->getFileStat( $params );
- wfProfileOut( __METHOD__ );
- return ( $stat === null ) ? null : (bool)$stat; // null => failure
- }
-
- /**
- * @see FileBackend::getFileTimestamp()
- */
- final public function getFileTimestamp( array $params ) {
- wfProfileIn( __METHOD__ );
- $stat = $this->getFileStat( $params );
- wfProfileOut( __METHOD__ );
- return $stat ? $stat['mtime'] : false;
- }
-
- /**
- * @see FileBackend::getFileSize()
- */
- final public function getFileSize( array $params ) {
- wfProfileIn( __METHOD__ );
- $stat = $this->getFileStat( $params );
- wfProfileOut( __METHOD__ );
- return $stat ? $stat['size'] : false;
- }
-
- /**
- * @see FileBackend::getFileStat()
- */
- final public function getFileStat( array $params ) {
- wfProfileIn( __METHOD__ );
- $path = self::normalizeStoragePath( $params['src'] );
- if ( $path === null ) {
- return false; // invalid storage path
- }
- $latest = !empty( $params['latest'] );
- if ( isset( $this->cache[$path]['stat'] ) ) {
- // If we want the latest data, check that this cached
- // value was in fact fetched with the latest available data.
- if ( !$latest || $this->cache[$path]['stat']['latest'] ) {
- wfProfileOut( __METHOD__ );
- return $this->cache[$path]['stat'];
- }
- }
- $stat = $this->doGetFileStat( $params );
- if ( is_array( $stat ) ) { // don't cache negatives
- $this->trimCache(); // limit memory
- $this->cache[$path]['stat'] = $stat;
- $this->cache[$path]['stat']['latest'] = $latest;
- }
- wfProfileOut( __METHOD__ );
- return $stat;
- }
-
- /**
- * @see FileBackendStore::getFileStat()
- */
- abstract protected function doGetFileStat( array $params );
-
- /**
- * @see FileBackend::getFileContents()
- */
- public function getFileContents( array $params ) {
- wfProfileIn( __METHOD__ );
- $tmpFile = $this->getLocalReference( $params );
- if ( !$tmpFile ) {
- wfProfileOut( __METHOD__ );
- return false;
- }
- wfSuppressWarnings();
- $data = file_get_contents( $tmpFile->getPath() );
- wfRestoreWarnings();
- wfProfileOut( __METHOD__ );
- return $data;
- }
-
- /**
- * @see FileBackend::getFileSha1Base36()
- */
- final public function getFileSha1Base36( array $params ) {
- wfProfileIn( __METHOD__ );
- $path = $params['src'];
- if ( isset( $this->cache[$path]['sha1'] ) ) {
- wfProfileOut( __METHOD__ );
- return $this->cache[$path]['sha1'];
- }
- $hash = $this->doGetFileSha1Base36( $params );
- if ( $hash ) { // don't cache negatives
- $this->trimCache(); // limit memory
- $this->cache[$path]['sha1'] = $hash;
- }
- wfProfileOut( __METHOD__ );
- return $hash;
- }
-
- /**
- * @see FileBackendStore::getFileSha1Base36()
- */
- protected function doGetFileSha1Base36( array $params ) {
- $fsFile = $this->getLocalReference( $params );
- if ( !$fsFile ) {
- return false;
- } else {
- return $fsFile->getSha1Base36();
- }
- }
-
- /**
- * @see FileBackend::getFileProps()
- */
- final public function getFileProps( array $params ) {
- wfProfileIn( __METHOD__ );
- $fsFile = $this->getLocalReference( $params );
- $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
- wfProfileOut( __METHOD__ );
- return $props;
- }
-
- /**
- * @see FileBackend::getLocalReference()
- */
- public function getLocalReference( array $params ) {
- wfProfileIn( __METHOD__ );
- $path = $params['src'];
- if ( isset( $this->expensiveCache[$path]['localRef'] ) ) {
- wfProfileOut( __METHOD__ );
- return $this->expensiveCache[$path]['localRef'];
- }
- $tmpFile = $this->getLocalCopy( $params );
- if ( $tmpFile ) { // don't cache negatives
- $this->trimExpensiveCache(); // limit memory
- $this->expensiveCache[$path]['localRef'] = $tmpFile;
- }
- wfProfileOut( __METHOD__ );
- return $tmpFile;
- }
-
- /**
- * @see FileBackend::streamFile()
- */
- final public function streamFile( array $params ) {
- wfProfileIn( __METHOD__ );
- $status = Status::newGood();
-
- $info = $this->getFileStat( $params );
- if ( !$info ) { // let StreamFile handle the 404
- $status->fatal( 'backend-fail-notexists', $params['src'] );
- }
-
- // Set output buffer and HTTP headers for stream
- $extraHeaders = isset( $params['headers'] ) ? $params['headers'] : array();
- $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
- if ( $res == StreamFile::NOT_MODIFIED ) {
- // do nothing; client cache is up to date
- } elseif ( $res == StreamFile::READY_STREAM ) {
- $status = $this->doStreamFile( $params );
- } else {
- $status->fatal( 'backend-fail-stream', $params['src'] );
- }
-
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackendStore::streamFile()
- */
- protected function doStreamFile( array $params ) {
- $status = Status::newGood();
-
- $fsFile = $this->getLocalReference( $params );
- if ( !$fsFile ) {
- $status->fatal( 'backend-fail-stream', $params['src'] );
- } elseif ( !readfile( $fsFile->getPath() ) ) {
- $status->fatal( 'backend-fail-stream', $params['src'] );
- }
-
- return $status;
- }
-
- /**
- * @copydoc FileBackend::getFileList()
- */
- final public function getFileList( array $params ) {
- list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
- if ( $dir === null ) { // invalid storage path
- return null;
- }
- if ( $shard !== null ) {
- // File listing is confined to a single container/shard
- return $this->getFileListInternal( $fullCont, $dir, $params );
- } else {
- wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
- // File listing spans multiple containers/shards
- list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
- return new FileBackendStoreShardListIterator( $this,
- $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
- }
- }
-
- /**
- * Do not call this function from places outside FileBackend
- *
- * @see FileBackendStore::getFileList()
- *
- * @param $container string Resolved container name
- * @param $dir string Resolved path relative to container
- * @param $params Array
- * @return Traversable|Array|null
- */
- abstract public function getFileListInternal( $container, $dir, array $params );
-
- /**
- * Get the list of supported operations and their corresponding FileOp classes.
- *
- * @return Array
- */
- protected function supportedOperations() {
- return array(
- 'store' => 'StoreFileOp',
- 'copy' => 'CopyFileOp',
- 'move' => 'MoveFileOp',
- 'delete' => 'DeleteFileOp',
- 'create' => 'CreateFileOp',
- 'null' => 'NullFileOp'
- );
- }
-
- /**
- * Return a list of FileOp objects from a list of operations.
- * Do not call this function from places outside FileBackend.
- *
- * The result must have the same number of items as the input.
- * An exception is thrown if an unsupported operation is requested.
- *
- * @param $ops Array Same format as doOperations()
- * @return Array List of FileOp objects
- * @throws MWException
- */
- final public function getOperations( array $ops ) {
- $supportedOps = $this->supportedOperations();
-
- $performOps = array(); // array of FileOp objects
- // Build up ordered array of FileOps...
- foreach ( $ops as $operation ) {
- $opName = $operation['op'];
- if ( isset( $supportedOps[$opName] ) ) {
- $class = $supportedOps[$opName];
- // Get params for this operation
- $params = $operation;
- // Append the FileOp class
- $performOps[] = new $class( $this, $params );
- } else {
- throw new MWException( "Operation `$opName` is not supported." );
- }
- }
-
- return $performOps;
- }
-
- /**
- * @see FileBackend::doOperationsInternal()
- */
- protected function doOperationsInternal( array $ops, array $opts ) {
- wfProfileIn( __METHOD__ );
- $status = Status::newGood();
-
- // Build up a list of FileOps...
- $performOps = $this->getOperations( $ops );
-
- // Acquire any locks as needed...
- if ( empty( $opts['nonLocking'] ) ) {
- // Build up a list of files to lock...
- $filesLockEx = $filesLockSh = array();
- foreach ( $performOps as $fileOp ) {
- $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
- $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
- }
- // Optimization: if doing an EX lock anyway, don't also set an SH one
- $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
- // Get a shared lock on the parent directory of each path changed
- $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
- // Try to lock those files for the scope of this function...
- $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager::LOCK_UW, $status );
- $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
- if ( !$status->isOK() ) {
- wfProfileOut( __METHOD__ );
- return $status; // abort
- }
- }
-
- // Clear any cache entries (after locks acquired)
- $this->clearCache();
-
- // Actually attempt the operation batch...
- $subStatus = FileOp::attemptBatch( $performOps, $opts );
-
- // Merge errors into status fields
- $status->merge( $subStatus );
- $status->success = $subStatus->success; // not done in merge()
-
- wfProfileOut( __METHOD__ );
- return $status;
- }
-
- /**
- * @see FileBackend::clearCache()
- */
- final public function clearCache( array $paths = null ) {
- if ( is_array( $paths ) ) {
- $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
- $paths = array_filter( $paths, 'strlen' ); // remove nulls
- }
- if ( $paths === null ) {
- $this->cache = array();
- $this->expensiveCache = array();
- } else {
- foreach ( $paths as $path ) {
- unset( $this->cache[$path] );
- unset( $this->expensiveCache[$path] );
- }
- }
- $this->doClearCache( $paths );
- }
-
- /**
- * Clears any additional stat caches for storage paths
- *
- * @see FileBackend::clearCache()
- *
- * @param $paths Array Storage paths (optional)
- * @return void
- */
- protected function doClearCache( array $paths = null ) {}
-
- /**
- * Prune the inexpensive cache if it is too big to add an item
- *
- * @return void
- */
- protected function trimCache() {
- if ( count( $this->cache ) >= $this->maxCacheSize ) {
- reset( $this->cache );
- unset( $this->cache[key( $this->cache )] );
- }
- }
-
- /**
- * Prune the expensive cache if it is too big to add an item
- *
- * @return void
- */
- protected function trimExpensiveCache() {
- if ( count( $this->expensiveCache ) >= $this->maxExpensiveCacheSize ) {
- reset( $this->expensiveCache );
- unset( $this->expensiveCache[key( $this->expensiveCache )] );
- }
- }
-
- /**
- * Check if a container name is valid.
- * This checks for for length and illegal characters.
- *
- * @param $container string
- * @return bool
- */
- final protected static function isValidContainerName( $container ) {
- // This accounts for Swift and S3 restrictions while leaving room
- // for things like '.xxx' (hex shard chars) or '.seg' (segments).
- // This disallows directory separators or traversal characters.
- // Note that matching strings URL encode to the same string;
- // in Swift, the length restriction is *after* URL encoding.
- return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
- }
-
- /**
- * Splits a storage path into an internal container name,
- * an internal relative file name, and a container shard suffix.
- * Any shard suffix is already appended to the internal container name.
- * This also checks that the storage path is valid and within this backend.
- *
- * If the container is sharded but a suffix could not be determined,
- * this means that the path can only refer to a directory and can only
- * be scanned by looking in all the container shards.
- *
- * @param $storagePath string
- * @return Array (container, path, container suffix) or (null, null, null) if invalid
- */
- final protected function resolveStoragePath( $storagePath ) {
- list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
- if ( $backend === $this->name ) { // must be for this backend
- $relPath = self::normalizeContainerPath( $relPath );
- if ( $relPath !== null ) {
- // Get shard for the normalized path if this container is sharded
- $cShard = $this->getContainerShard( $container, $relPath );
- // Validate and sanitize the relative path (backend-specific)
- $relPath = $this->resolveContainerPath( $container, $relPath );
- if ( $relPath !== null ) {
- // Prepend any wiki ID prefix to the container name
- $container = $this->fullContainerName( $container );
- if ( self::isValidContainerName( $container ) ) {
- // Validate and sanitize the container name (backend-specific)
- $container = $this->resolveContainerName( "{$container}{$cShard}" );
- if ( $container !== null ) {
- return array( $container, $relPath, $cShard );
- }
- }
- }
- }
- }
- return array( null, null, null );
- }
-
- /**
- * Like resolveStoragePath() except null values are returned if
- * the container is sharded and the shard could not be determined.
- *
- * @see FileBackendStore::resolveStoragePath()
- *
- * @param $storagePath string
- * @return Array (container, path) or (null, null) if invalid
- */
- final protected function resolveStoragePathReal( $storagePath ) {
- list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
- if ( $cShard !== null ) {
- return array( $container, $relPath );
- }
- return array( null, null );
- }
-
- /**
- * Get the container name shard suffix for a given path.
- * Any empty suffix means the container is not sharded.
- *
- * @param $container string Container name
- * @param $relStoragePath string Storage path relative to the container
- * @return string|null Returns null if shard could not be determined
- */
- final protected function getContainerShard( $container, $relPath ) {
- list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
- if ( $levels == 1 || $levels == 2 ) {
- // Hash characters are either base 16 or 36
- $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
- // Get a regex that represents the shard portion of paths.
- // The concatenation of the captures gives us the shard.
- if ( $levels === 1 ) { // 16 or 36 shards per container
- $hashDirRegex = '(' . $char . ')';
- } else { // 256 or 1296 shards per container
- if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
- $hashDirRegex = $char . '/(' . $char . '{2})';
- } else { // short hash dir format (e.g. "a/b/c")
- $hashDirRegex = '(' . $char . ')/(' . $char . ')';
- }
- }
- // Allow certain directories to be above the hash dirs so as
- // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
- // They must be 2+ chars to avoid any hash directory ambiguity.
- $m = array();
- if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
- return '.' . implode( '', array_slice( $m, 1 ) );
- }
- return null; // failed to match
- }
- return ''; // no sharding
- }
-
- /**
- * Get the sharding config for a container.
- * If greater than 0, then all file storage paths within
- * the container are required to be hashed accordingly.
- *
- * @param $container string
- * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
- */
- final protected function getContainerHashLevels( $container ) {
- if ( isset( $this->shardViaHashLevels[$container] ) ) {
- $config = $this->shardViaHashLevels[$container];
- $hashLevels = (int)$config['levels'];
- if ( $hashLevels == 1 || $hashLevels == 2 ) {
- $hashBase = (int)$config['base'];
- if ( $hashBase == 16 || $hashBase == 36 ) {
- return array( $hashLevels, $hashBase, $config['repeat'] );
- }
- }
- }
- return array( 0, 0, false ); // no sharding
- }
-
- /**
- * Get a list of full container shard suffixes for a container
- *
- * @param $container string
- * @return Array
- */
- final protected function getContainerSuffixes( $container ) {
- $shards = array();
- list( $digits, $base ) = $this->getContainerHashLevels( $container );
- if ( $digits > 0 ) {
- $numShards = pow( $base, $digits );
- for ( $index = 0; $index < $numShards; $index++ ) {
- $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
- }
- }
- return $shards;
- }
-
- /**
- * Get the full container name, including the wiki ID prefix
- *
- * @param $container string
- * @return string
- */
- final protected function fullContainerName( $container ) {
- if ( $this->wikiId != '' ) {
- return "{$this->wikiId}-$container";
- } else {
- return $container;
- }
- }
-
- /**
- * Resolve a container name, checking if it's allowed by the backend.
- * This is intended for internal use, such as encoding illegal chars.
- * Subclasses can override this to be more restrictive.
- *
- * @param $container string
- * @return string|null
- */
- protected function resolveContainerName( $container ) {
- return $container;
- }
-
- /**
- * Resolve a relative storage path, checking if it's allowed by the backend.
- * This is intended for internal use, such as encoding illegal chars or perhaps
- * getting absolute paths (e.g. FS based backends). Note that the relative path
- * may be the empty string (e.g. the path is simply to the container).
- *
- * @param $container string Container name
- * @param $relStoragePath string Storage path relative to the container
- * @return string|null Path or null if not valid
- */
- protected function resolveContainerPath( $container, $relStoragePath ) {
- return $relStoragePath;
- }
-}
-
-/**
- * FileBackendStore helper function to handle file listings that span container shards.
- * Do not use this class from places outside of FileBackendStore.
- *
- * @ingroup FileBackend
- */
-class FileBackendStoreShardListIterator implements Iterator {
- /* @var FileBackendStore */
- protected $backend;
- /* @var Array */
- protected $params;
- /* @var Array */
- protected $shardSuffixes;
- protected $container; // string
- protected $directory; // string
-
- /* @var Traversable */
- protected $iter;
- protected $curShard = 0; // integer
- protected $pos = 0; // integer
-
- /**
- * @param $backend FileBackendStore
- * @param $container string Full storage container name
- * @param $dir string Storage directory relative to container
- * @param $suffixes Array List of container shard suffixes
- * @param $params Array
- */
- public function __construct(
- FileBackendStore $backend, $container, $dir, array $suffixes, array $params
- ) {
- $this->backend = $backend;
- $this->container = $container;
- $this->directory = $dir;
- $this->shardSuffixes = $suffixes;
- $this->params = $params;
- }
-
- public function current() {
- if ( is_array( $this->iter ) ) {
- return current( $this->iter );
- } else {
- return $this->iter->current();
- }
- }
-
- public function key() {
- return $this->pos;
- }
-
- public function next() {
- ++$this->pos;
- if ( is_array( $this->iter ) ) {
- next( $this->iter );
- } else {
- $this->iter->next();
- }
- // Find the next non-empty shard if no elements are left
- $this->nextShardIteratorIfNotValid();
- }
-
- /**
- * If the iterator for this container shard is out of items,
- * then move on to the next container that has items.
- * If there are none, then it advances to the last container.
- */
- protected function nextShardIteratorIfNotValid() {
- while ( !$this->valid() ) {
- if ( ++$this->curShard >= count( $this->shardSuffixes ) ) {
- break; // no more container shards
- }
- $this->setIteratorFromCurrentShard();
- }
- }
-
- protected function setIteratorFromCurrentShard() {
- $suffix = $this->shardSuffixes[$this->curShard];
- $this->iter = $this->backend->getFileListInternal(
- "{$this->container}{$suffix}", $this->directory, $this->params );
- }
-
- public function rewind() {
- $this->pos = 0;
- $this->curShard = 0;
- $this->setIteratorFromCurrentShard();
- // Find the next non-empty shard if this one has no elements
- $this->nextShardIteratorIfNotValid();
- }
-
- public function valid() {
- if ( $this->iter == null ) {
- return false; // some failure?
- } elseif ( is_array( $this->iter ) ) {
- return ( current( $this->iter ) !== false ); // no paths can have this value
- } else {
- return $this->iter->valid();
- }
- }
-}
diff --git a/includes/filerepo/backend/FileBackendGroup.php b/includes/filerepo/backend/FileBackendGroup.php
deleted file mode 100644
index 73815cfb..00000000
--- a/includes/filerepo/backend/FileBackendGroup.php
+++ /dev/null
@@ -1,156 +0,0 @@
-<?php
-/**
- * @file
- * @ingroup FileBackend
- * @author Aaron Schulz
- */
-
-/**
- * Class to handle file backend registration
- *
- * @ingroup FileBackend
- * @since 1.19
- */
-class FileBackendGroup {
- /**
- * @var FileBackendGroup
- */
- protected static $instance = null;
-
- /** @var Array (name => ('class' => string, 'config' => array, 'instance' => object)) */
- protected $backends = array();
-
- protected function __construct() {}
- protected function __clone() {}
-
- /**
- * @return FileBackendGroup
- */
- public static function singleton() {
- if ( self::$instance == null ) {
- self::$instance = new self();
- self::$instance->initFromGlobals();
- }
- return self::$instance;
- }
-
- /**
- * Destroy the singleton instance
- *
- * @return void
- */
- public static function destroySingleton() {
- self::$instance = null;
- }
-
- /**
- * Register file backends from the global variables
- *
- * @return void
- */
- protected function initFromGlobals() {
- global $wgLocalFileRepo, $wgForeignFileRepos, $wgFileBackends;
-
- // Register explicitly defined backends
- $this->register( $wgFileBackends );
-
- $autoBackends = array();
- // Automatically create b/c backends for file repos...
- $repos = array_merge( $wgForeignFileRepos, array( $wgLocalFileRepo ) );
- foreach ( $repos as $info ) {
- $backendName = $info['backend'];
- if ( is_object( $backendName ) || isset( $this->backends[$backendName] ) ) {
- continue; // already defined (or set to the object for some reason)
- }
- $repoName = $info['name'];
- // Local vars that used to be FSRepo members...
- $directory = $info['directory'];
- $deletedDir = isset( $info['deletedDir'] )
- ? $info['deletedDir']
- : false; // deletion disabled
- $thumbDir = isset( $info['thumbDir'] )
- ? $info['thumbDir']
- : "{$directory}/thumb";
- $fileMode = isset( $info['fileMode'] )
- ? $info['fileMode']
- : 0644;
- // Get the FS backend configuration
- $autoBackends[] = array(
- 'name' => $backendName,
- 'class' => 'FSFileBackend',
- 'lockManager' => 'fsLockManager',
- 'containerPaths' => array(
- "{$repoName}-public" => "{$directory}",
- "{$repoName}-thumb" => $thumbDir,
- "{$repoName}-deleted" => $deletedDir,
- "{$repoName}-temp" => "{$directory}/temp"
- ),
- 'fileMode' => $fileMode,
- );
- }
-
- // Register implicitly defined backends
- $this->register( $autoBackends );
- }
-
- /**
- * Register an array of file backend configurations
- *
- * @param $configs Array
- * @return void
- * @throws MWException
- */
- protected function register( array $configs ) {
- foreach ( $configs as $config ) {
- if ( !isset( $config['name'] ) ) {
- throw new MWException( "Cannot register a backend with no name." );
- }
- $name = $config['name'];
- if ( !isset( $config['class'] ) ) {
- throw new MWException( "Cannot register backend `{$name}` with no class." );
- }
- $class = $config['class'];
-
- unset( $config['class'] ); // backend won't need this
- $this->backends[$name] = array(
- 'class' => $class,
- 'config' => $config,
- 'instance' => null
- );
- }
- }
-
- /**
- * Get the backend object with a given name
- *
- * @param $name string
- * @return FileBackend
- * @throws MWException
- */
- public function get( $name ) {
- if ( !isset( $this->backends[$name] ) ) {
- throw new MWException( "No backend defined with the name `$name`." );
- }
- // Lazy-load the actual backend instance
- if ( !isset( $this->backends[$name]['instance'] ) ) {
- $class = $this->backends[$name]['class'];
- $config = $this->backends[$name]['config'];
- $this->backends[$name]['instance'] = new $class( $config );
- }
- return $this->backends[$name]['instance'];
- }
-
- /**
- * Get an appropriate backend object from a storage path
- *
- * @param $storagePath string
- * @return FileBackend|null Backend or null on failure
- */
- public function backendFromPath( $storagePath ) {
- list( $backend, $c, $p ) = FileBackend::splitStoragePath( $storagePath );
- if ( $backend !== null && isset( $this->backends[$backend] ) ) {
- return $this->get( $backend );
- }
- return null;
- }
-}
diff --git a/includes/filerepo/backend/FileBackendMultiWrite.php b/includes/filerepo/backend/FileBackendMultiWrite.php
deleted file mode 100644
index c0f1ac57..00000000
--- a/includes/filerepo/backend/FileBackendMultiWrite.php
+++ /dev/null
@@ -1,420 +0,0 @@
-<?php
-/**
- * @file
- * @ingroup FileBackend
- * @author Aaron Schulz
- */
-
-/**
- * This class defines a multi-write backend. Multiple backends can be
- * registered to this proxy backend and it will act as a single backend.
- * Use this when all access to those backends is through this proxy backend.
- * At least one of the backends must be declared the "master" backend.
- *
- * Only use this class when transitioning from one storage system to another.
- *
- * Read operations are only done on the 'master' backend for consistency.
- * Write operations are performed on all backends, in the order defined.
- * If an operation fails on one backend it will be rolled back from the others.
- *
- * @ingroup FileBackend
- * @since 1.19
- */
-class FileBackendMultiWrite extends FileBackend {
- /** @var Array Prioritized list of FileBackendStore objects */
- protected $backends = array(); // array of (backend index => backends)
- protected $masterIndex = -1; // integer; index of master backend
- protected $syncChecks = 0; // integer bitfield
-
- /* Possible internal backend consistency checks */
- const CHECK_SIZE = 1;
- const CHECK_TIME = 2;
-
- /**
- * Construct a proxy backend that consists of several internal backends.
- * Additional $config params include:
- * 'backends' : Array of backend config and multi-backend settings.
- * Each value is the config used in the constructor of a
- * FileBackendStore class, but with these additional settings:
- * 'class' : The name of the backend class
- * 'isMultiMaster' : This must be set for one backend.
- * 'syncChecks' : Integer bitfield of internal backend sync checks to perform.
- * Possible bits include self::CHECK_SIZE and self::CHECK_TIME.
- * The checks are done before allowing any file operations.
- * @param $config Array
- */
- public function __construct( array $config ) {
- parent::__construct( $config );
- $namesUsed = array();
- // Construct backends here rather than via registration
- // to keep these backends hidden from outside the proxy.
- foreach ( $config['backends'] as $index => $config ) {
- $name = $config['name'];
- if ( isset( $namesUsed[$name] ) ) { // don't break FileOp predicates
- throw new MWException( "Two or more backends defined with the name $name." );
- }
- $namesUsed[$name] = 1;
- if ( !isset( $config['class'] ) ) {
- throw new MWException( 'No class given for a backend config.' );
- }
- $class = $config['class'];
- $this->backends[$index] = new $class( $config );
- if ( !empty( $config['isMultiMaster'] ) ) {
- if ( $this->masterIndex >= 0 ) {
- throw new MWException( 'More than one master backend defined.' );
- }
- $this->masterIndex = $index;
- }
- }
- if ( $this->masterIndex < 0 ) { // need backends and must have a master
- throw new MWException( 'No master backend defined.' );
- }
- $this->syncChecks = isset( $config['syncChecks'] )
- ? $config['syncChecks']
- : self::CHECK_SIZE;
- }
-
- /**
- * @see FileBackend::doOperationsInternal()
- */
- final protected function doOperationsInternal( array $ops, array $opts ) {
- $status = Status::newGood();
-
- $performOps = array(); // list of FileOp objects
- $filesRead = $filesChanged = array(); // storage paths used
- // Build up a list of FileOps. The list will have all the ops
- // for one backend, then all the ops for the next, and so on.
- // These batches of ops are all part of a continuous array.
- // Also build up a list of files read/changed...
- foreach ( $this->backends as $index => $backend ) {
- $backendOps = $this->substOpBatchPaths( $ops, $backend );
- // Add on the operation batch for this backend
- $performOps = array_merge( $performOps, $backend->getOperations( $backendOps ) );
- if ( $index == 0 ) { // first batch
- // Get the files used for these operations. Each backend has a batch of
- // the same operations, so we only need to get them from the first batch.
- foreach ( $performOps as $fileOp ) {
- $filesRead = array_merge( $filesRead, $fileOp->storagePathsRead() );
- $filesChanged = array_merge( $filesChanged, $fileOp->storagePathsChanged() );
- }
- // Get the paths under the proxy backend's name
- $filesRead = $this->unsubstPaths( $filesRead );
- $filesChanged = $this->unsubstPaths( $filesChanged );
- }
- }
-
- // Try to lock those files for the scope of this function...
- if ( empty( $opts['nonLocking'] ) ) {
- $filesLockSh = array_diff( $filesRead, $filesChanged ); // optimization
- $filesLockEx = $filesChanged;
- // Get a shared lock on the parent directory of each path changed
- $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
- // Try to lock those files for the scope of this function...
- $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager::LOCK_UW, $status );
- $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
- if ( !$status->isOK() ) {
- return $status; // abort
- }
- }
-
- // Clear any cache entries (after locks acquired)
- $this->clearCache();
-
- // Do a consistency check to see if the backends agree
- if ( count( $this->backends ) > 1 ) {
- $status->merge( $this->consistencyCheck( array_merge( $filesRead, $filesChanged ) ) );
- if ( !$status->isOK() ) {
- return $status; // abort
- }
- }
-
- // Actually attempt the operation batch...
- $subStatus = FileOp::attemptBatch( $performOps, $opts );
-
- $success = array();
- $failCount = $successCount = 0;
- // Make 'success', 'successCount', and 'failCount' fields reflect
- // the overall operation, rather than all the batches for each backend.
- // Do this by only using success values from the master backend's batch.
- $batchStart = $this->masterIndex * count( $ops );
- $batchEnd = $batchStart + count( $ops ) - 1;
- for ( $i = $batchStart; $i <= $batchEnd; $i++ ) {
- if ( !isset( $subStatus->success[$i] ) ) {
- break; // failed out before trying this op
- } elseif ( $subStatus->success[$i] ) {
- ++$successCount;
- } else {
- ++$failCount;
- }
- $success[] = $subStatus->success[$i];
- }
- $subStatus->success = $success;
- $subStatus->successCount = $successCount;
- $subStatus->failCount = $failCount;
-
- // Merge errors into status fields
- $status->merge( $subStatus );
- $status->success = $subStatus->success; // not done in merge()
-
- return $status;
- }
-
- /**
- * Check that a set of files are consistent across all internal backends
- *
- * @param $paths Array
- * @return Status
- */
- public function consistencyCheck( array $paths ) {
- $status = Status::newGood();
- if ( $this->syncChecks == 0 ) {
- return $status; // skip checks
- }
-
- $mBackend = $this->backends[$this->masterIndex];
- foreach ( array_unique( $paths ) as $path ) {
- $params = array( 'src' => $path, 'latest' => true );
- // Stat the file on the 'master' backend
- $mStat = $mBackend->getFileStat( $this->substOpPaths( $params, $mBackend ) );
- // Check of all clone backends agree with the master...
- foreach ( $this->backends as $index => $cBackend ) {
- if ( $index === $this->masterIndex ) {
- continue; // master
- }
- $cStat = $cBackend->getFileStat( $this->substOpPaths( $params, $cBackend ) );
- if ( $mStat ) { // file is in master
- if ( !$cStat ) { // file should exist
- $status->fatal( 'backend-fail-synced', $path );
- continue;
- }
- if ( $this->syncChecks & self::CHECK_SIZE ) {
- if ( $cStat['size'] != $mStat['size'] ) { // wrong size
- $status->fatal( 'backend-fail-synced', $path );
- continue;
- }
- }
- if ( $this->syncChecks & self::CHECK_TIME ) {
- $mTs = wfTimestamp( TS_UNIX, $mStat['mtime'] );
- $cTs = wfTimestamp( TS_UNIX, $cStat['mtime'] );
- if ( abs( $mTs - $cTs ) > 30 ) { // outdated file somewhere
- $status->fatal( 'backend-fail-synced', $path );
- continue;
- }
- }
- } else { // file is not in master
- if ( $cStat ) { // file should not exist
- $status->fatal( 'backend-fail-synced', $path );
- }
- }
- }
- }
-
- return $status;
- }
-
- /**
- * Substitute the backend name in storage path parameters
- * for a set of operations with that of a given internal backend.
- *
- * @param $ops Array List of file operation arrays
- * @param $backend FileBackendStore
- * @return Array
- */
- protected function substOpBatchPaths( array $ops, FileBackendStore $backend ) {
- $newOps = array(); // operations
- foreach ( $ops as $op ) {
- $newOp = $op; // operation
- foreach ( array( 'src', 'srcs', 'dst', 'dir' ) as $par ) {
- if ( isset( $newOp[$par] ) ) { // string or array
- $newOp[$par] = $this->substPaths( $newOp[$par], $backend );
- }
- }
- $newOps[] = $newOp;
- }
- return $newOps;
- }
-
- /**
- * Same as substOpBatchPaths() but for a single operation
- *
- * @param $op File operation array
- * @param $backend FileBackendStore
- * @return Array
- */
- protected function substOpPaths( array $ops, FileBackendStore $backend ) {
- $newOps = $this->substOpBatchPaths( array( $ops ), $backend );
- return $newOps[0];
- }
-
- /**
- * Substitute the backend of storage paths with an internal backend's name
- *
- * @param $paths Array|string List of paths or single string path
- * @param $backend FileBackendStore
- * @return Array|string
- */
- protected function substPaths( $paths, FileBackendStore $backend ) {
- return preg_replace(
- '!^mwstore://' . preg_quote( $this->name ) . '/!',
- StringUtils::escapeRegexReplacement( "mwstore://{$backend->getName()}/" ),
- $paths // string or array
- );
- }
-
- /**
- * Substitute the backend of internal storage paths with the proxy backend's name
- *
- * @param $paths Array|string List of paths or single string path
- * @return Array|string
- */
- protected function unsubstPaths( $paths ) {
- return preg_replace(
- '!^mwstore://([^/]+)!',
- StringUtils::escapeRegexReplacement( "mwstore://{$this->name}" ),
- $paths // string or array
- );
- }
-
- /**
- * @see FileBackend::doPrepare()
- */
- public function doPrepare( array $params ) {
- $status = Status::newGood();
- foreach ( $this->backends as $backend ) {
- $realParams = $this->substOpPaths( $params, $backend );
- $status->merge( $backend->doPrepare( $realParams ) );
- }
- return $status;
- }
-
- /**
- * @see FileBackend::doSecure()
- */
- public function doSecure( array $params ) {
- $status = Status::newGood();
- foreach ( $this->backends as $backend ) {
- $realParams = $this->substOpPaths( $params, $backend );
- $status->merge( $backend->doSecure( $realParams ) );
- }
- return $status;
- }
-
- /**
- * @see FileBackend::doClean()
- */
- public function doClean( array $params ) {
- $status = Status::newGood();
- foreach ( $this->backends as $backend ) {
- $realParams = $this->substOpPaths( $params, $backend );
- $status->merge( $backend->doClean( $realParams ) );
- }
- return $status;
- }
-
- /**
- * @see FileBackend::getFileList()
- */
- public function concatenate( array $params ) {
- // We are writing to an FS file, so we don't need to do this per-backend
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->concatenate( $realParams );
- }
-
- /**
- * @see FileBackend::fileExists()
- */
- public function fileExists( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->fileExists( $realParams );
- }
-
- /**
- * @see FileBackend::getFileTimestamp()
- */
- public function getFileTimestamp( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getFileTimestamp( $realParams );
- }
-
- /**
- * @see FileBackend::getFileSize()
- */
- public function getFileSize( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getFileSize( $realParams );
- }
-
- /**
- * @see FileBackend::getFileStat()
- */
- public function getFileStat( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getFileStat( $realParams );
- }
-
- /**
- * @see FileBackend::getFileContents()
- */
- public function getFileContents( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getFileContents( $realParams );
- }
-
- /**
- * @see FileBackend::getFileSha1Base36()
- */
- public function getFileSha1Base36( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getFileSha1Base36( $realParams );
- }
-
- /**
- * @see FileBackend::getFileProps()
- */
- public function getFileProps( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getFileProps( $realParams );
- }
-
- /**
- * @see FileBackend::streamFile()
- */
- public function streamFile( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->streamFile( $realParams );
- }
-
- /**
- * @see FileBackend::getLocalReference()
- */
- public function getLocalReference( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getLocalReference( $realParams );
- }
-
- /**
- * @see FileBackend::getLocalCopy()
- */
- public function getLocalCopy( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getLocalCopy( $realParams );
- }
-
- /**
- * @see FileBackend::getFileList()
- */
- public function getFileList( array $params ) {
- $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
- return $this->backends[$this->masterIndex]->getFileList( $realParams );
- }
-
- /**
- * @see FileBackend::clearCache()
- */
- public function clearCache( array $paths = null ) {
- foreach ( $this->backends as $backend ) {
- $realPaths = is_array( $paths ) ? $this->substPaths( $paths, $backend ) : null;
- $backend->clearCache( $realPaths );
- }
- }
-}
diff --git a/includes/filerepo/backend/FileOp.php b/includes/filerepo/backend/FileOp.php
deleted file mode 100644
index 5844c9f2..00000000
--- a/includes/filerepo/backend/FileOp.php
+++ /dev/null
@@ -1,697 +0,0 @@
-<?php
-/**
- * @file
- * @ingroup FileBackend
- * @author Aaron Schulz
- */
-
-/**
- * Helper class for representing operations with transaction support.
- * Do not use this class from places outside FileBackend.
- *
- * Methods called from attemptBatch() should avoid throwing exceptions at all costs.
- * FileOp objects should be lightweight in order to support large arrays in memory.
- *
- * @ingroup FileBackend
- * @since 1.19
- */
-abstract class FileOp {
- /** @var Array */
- protected $params = array();
- /** @var FileBackendStore */
- protected $backend;
-
- protected $state = self::STATE_NEW; // integer
- protected $failed = false; // boolean
- protected $useLatest = true; // boolean
-
- protected $sourceSha1; // string
- protected $destSameAsSource; // boolean
-
- /* Object life-cycle */
- const STATE_NEW = 1;
- const STATE_CHECKED = 2;
- const STATE_ATTEMPTED = 3;
-
- /* Timeout related parameters */
- const MAX_BATCH_SIZE = 1000;
- const TIME_LIMIT_SEC = 300; // 5 minutes
-
- /**
- * Build a new file operation transaction
- *
- * @params $backend FileBackendStore
- * @params $params Array
- * @throws MWException
- */
- final public function __construct( FileBackendStore $backend, array $params ) {
- $this->backend = $backend;
- list( $required, $optional ) = $this->allowedParams();
- foreach ( $required as $name ) {
- if ( isset( $params[$name] ) ) {
- $this->params[$name] = $params[$name];
- } else {
- throw new MWException( "File operation missing parameter '$name'." );
- }
- }
- foreach ( $optional as $name ) {
- if ( isset( $params[$name] ) ) {
- $this->params[$name] = $params[$name];
- }
- }
- $this->params = $params;
- }
-
- /**
- * Allow stale data for file reads and existence checks
- *
- * @return void
- */
- final protected function allowStaleReads() {
- $this->useLatest = false;
- }
-
- /**
- * Attempt a series of file operations.
- * Callers are responsible for handling file locking.
- *
- * $opts is an array of options, including:
- * 'force' : Errors that would normally cause a rollback do not.
- * The remaining operations are still attempted if any fail.
- * 'allowStale' : Don't require the latest available data.
- * This can increase performance for non-critical writes.
- * This has no effect unless the 'force' flag is set.
- *
- * The resulting Status will be "OK" unless:
- * a) unexpected operation errors occurred (network partitions, disk full...)
- * b) significant operation errors occured and 'force' was not set
- *
- * @param $performOps Array List of FileOp operations
- * @param $opts Array Batch operation options
- * @return Status
- */
- final public static function attemptBatch( array $performOps, array $opts ) {
- $status = Status::newGood();
-
- $allowStale = !empty( $opts['allowStale'] );
- $ignoreErrors = !empty( $opts['force'] );
-
- $n = count( $performOps );
- if ( $n > self::MAX_BATCH_SIZE ) {
- $status->fatal( 'backend-fail-batchsize', $n, self::MAX_BATCH_SIZE );
- return $status;
- }
-
- $predicates = FileOp::newPredicates(); // account for previous op in prechecks
- // Do pre-checks for each operation; abort on failure...
- foreach ( $performOps as $index => $fileOp ) {
- if ( $allowStale ) {
- $fileOp->allowStaleReads(); // allow potentially stale reads
- }
- $subStatus = $fileOp->precheck( $predicates );
- $status->merge( $subStatus );
- if ( !$subStatus->isOK() ) { // operation failed?
- $status->success[$index] = false;
- ++$status->failCount;
- if ( !$ignoreErrors ) {
- return $status; // abort
- }
- }
- }
-
- if ( $ignoreErrors ) {
- # Treat all precheck() fatals as merely warnings
- $status->setResult( true, $status->value );
- }
-
- // Restart PHP's execution timer and set the timeout to safe amount.
- // This handles cases where the operations take a long time or where we are
- // already running low on time left. The old timeout is restored afterwards.
- # @TODO: re-enable this for when the number of batches is high.
- #$scopedTimeLimit = new FileOpScopedPHPTimeout( self::TIME_LIMIT_SEC );
-
- // Attempt each operation...
- foreach ( $performOps as $index => $fileOp ) {
- if ( $fileOp->failed() ) {
- continue; // nothing to do
- }
- $subStatus = $fileOp->attempt();
- $status->merge( $subStatus );
- if ( $subStatus->isOK() ) {
- $status->success[$index] = true;
- ++$status->successCount;
- } else {
- $status->success[$index] = false;
- ++$status->failCount;
- // We can't continue (even with $ignoreErrors) as $predicates is wrong.
- // Log the remaining ops as failed for recovery...
- for ( $i = ($index + 1); $i < count( $performOps ); $i++ ) {
- $performOps[$i]->logFailure( 'attempt_aborted' );
- }
- return $status; // bail out
- }
- }
-
- return $status;
- }
-
- /**
- * Get the value of the parameter with the given name
- *
- * @param $name string
- * @return mixed Returns null if the parameter is not set
- */
- final public function getParam( $name ) {
- return isset( $this->params[$name] ) ? $this->params[$name] : null;
- }
-
- /**
- * Check if this operation failed precheck() or attempt()
- *
- * @return bool
- */
- final public function failed() {
- return $this->failed;
- }
-
- /**
- * Get a new empty predicates array for precheck()
- *
- * @return Array
- */
- final public static function newPredicates() {
- return array( 'exists' => array(), 'sha1' => array() );
- }
-
- /**
- * Check preconditions of the operation without writing anything
- *
- * @param $predicates Array
- * @return Status
- */
- final public function precheck( array &$predicates ) {
- if ( $this->state !== self::STATE_NEW ) {
- return Status::newFatal( 'fileop-fail-state', self::STATE_NEW, $this->state );
- }
- $this->state = self::STATE_CHECKED;
- $status = $this->doPrecheck( $predicates );
- if ( !$status->isOK() ) {
- $this->failed = true;
- }
- return $status;
- }
-
- /**
- * Attempt the operation, backing up files as needed; this must be reversible
- *
- * @return Status
- */
- final public function attempt() {
- if ( $this->state !== self::STATE_CHECKED ) {
- return Status::newFatal( 'fileop-fail-state', self::STATE_CHECKED, $this->state );
- } elseif ( $this->failed ) { // failed precheck
- return Status::newFatal( 'fileop-fail-attempt-precheck' );
- }
- $this->state = self::STATE_ATTEMPTED;
- $status = $this->doAttempt();
- if ( !$status->isOK() ) {
- $this->failed = true;
- $this->logFailure( 'attempt' );
- }
- return $status;
- }
-
- /**
- * Get the file operation parameters
- *
- * @return Array (required params list, optional params list)
- */
- protected function allowedParams() {
- return array( array(), array() );
- }
-
- /**
- * Get a list of storage paths read from for this operation
- *
- * @return Array
- */
- public function storagePathsRead() {
- return array();
- }
-
- /**
- * Get a list of storage paths written to for this operation
- *
- * @return Array
- */
- public function storagePathsChanged() {
- return array();
- }
-
- /**
- * @return Status
- */
- protected function doPrecheck( array &$predicates ) {
- return Status::newGood();
- }
-
- /**
- * @return Status
- */
- protected function doAttempt() {
- return Status::newGood();
- }
-
- /**
- * Check for errors with regards to the destination file already existing.
- * This also updates the destSameAsSource and sourceSha1 member variables.
- * A bad status will be returned if there is no chance it can be overwritten.
- *
- * @param $predicates Array
- * @return Status
- */
- protected function precheckDestExistence( array $predicates ) {
- $status = Status::newGood();
- // Get hash of source file/string and the destination file
- $this->sourceSha1 = $this->getSourceSha1Base36(); // FS file or data string
- if ( $this->sourceSha1 === null ) { // file in storage?
- $this->sourceSha1 = $this->fileSha1( $this->params['src'], $predicates );
- }
- $this->destSameAsSource = false;
- if ( $this->fileExists( $this->params['dst'], $predicates ) ) {
- if ( $this->getParam( 'overwrite' ) ) {
- return $status; // OK
- } elseif ( $this->getParam( 'overwriteSame' ) ) {
- $dhash = $this->fileSha1( $this->params['dst'], $predicates );
- // Check if hashes are valid and match each other...
- if ( !strlen( $this->sourceSha1 ) || !strlen( $dhash ) ) {
- $status->fatal( 'backend-fail-hashes' );
- } elseif ( $this->sourceSha1 !== $dhash ) {
- // Give an error if the files are not identical
- $status->fatal( 'backend-fail-notsame', $this->params['dst'] );
- } else {
- $this->destSameAsSource = true; // OK
- }
- return $status; // do nothing; either OK or bad status
- } else {
- $status->fatal( 'backend-fail-alreadyexists', $this->params['dst'] );
- return $status;
- }
- }
- return $status;
- }
-
- /**
- * precheckDestExistence() helper function to get the source file SHA-1.
- * Subclasses should overwride this iff the source is not in storage.
- *
- * @return string|false Returns false on failure
- */
- protected function getSourceSha1Base36() {
- return null; // N/A
- }
-
- /**
- * Check if a file will exist in storage when this operation is attempted
- *
- * @param $source string Storage path
- * @param $predicates Array
- * @return bool
- */
- final protected function fileExists( $source, array $predicates ) {
- if ( isset( $predicates['exists'][$source] ) ) {
- return $predicates['exists'][$source]; // previous op assures this
- } else {
- $params = array( 'src' => $source, 'latest' => $this->useLatest );
- return $this->backend->fileExists( $params );
- }
- }
-
- /**
- * Get the SHA-1 of a file in storage when this operation is attempted
- *
- * @param $source string Storage path
- * @param $predicates Array
- * @return string|false
- */
- final protected function fileSha1( $source, array $predicates ) {
- if ( isset( $predicates['sha1'][$source] ) ) {
- return $predicates['sha1'][$source]; // previous op assures this
- } else {
- $params = array( 'src' => $source, 'latest' => $this->useLatest );
- return $this->backend->getFileSha1Base36( $params );
- }
- }
-
- /**
- * Log a file operation failure and preserve any temp files
- *
- * @param $action string
- * @return void
- */
- final protected function logFailure( $action ) {
- $params = $this->params;
- $params['failedAction'] = $action;
- try {
- wfDebugLog( 'FileOperation',
- get_class( $this ) . ' failed:' . serialize( $params ) );
- } catch ( Exception $e ) {
- // bad config? debug log error?
- }
- }
-}
-
-/**
- * FileOp helper class to expand PHP execution time for a function.
- * On construction, set_time_limit() is called and set to $seconds.
- * When the object goes out of scope, the timer is restarted, with
- * the original time limit minus the time the object existed.
- */
-class FileOpScopedPHPTimeout {
- protected $startTime; // float; seconds
- protected $oldTimeout; // integer; seconds
-
- protected static $stackDepth = 0; // integer
- protected static $totalCalls = 0; // integer
- protected static $totalElapsed = 0; // float; seconds
-
- /* Prevent callers in infinite loops from running forever */
- const MAX_TOTAL_CALLS = 1000000;
- const MAX_TOTAL_TIME = 300; // seconds
-
- /**
- * @param $seconds integer
- */
- public function __construct( $seconds ) {
- if ( ini_get( 'max_execution_time' ) > 0 ) { // CLI uses 0
- if ( self::$totalCalls >= self::MAX_TOTAL_CALLS ) {
- trigger_error( "Maximum invocations of " . __CLASS__ . " exceeded." );
- } elseif ( self::$totalElapsed >= self::MAX_TOTAL_TIME ) {
- trigger_error( "Time limit within invocations of " . __CLASS__ . " exceeded." );
- } elseif ( self::$stackDepth > 0 ) { // recursion guard
- trigger_error( "Resursive invocation of " . __CLASS__ . " attempted." );
- } else {
- $this->oldTimeout = ini_set( 'max_execution_time', $seconds );
- $this->startTime = microtime( true );
- ++self::$stackDepth;
- ++self::$totalCalls; // proof against < 1us scopes
- }
- }
- }
-
- /**
- * Restore the original timeout.
- * This does not account for the timer value on __construct().
- */
- public function __destruct() {
- if ( $this->oldTimeout ) {
- $elapsed = microtime( true ) - $this->startTime;
- // Note: a limit of 0 is treated as "forever"
- set_time_limit( max( 1, $this->oldTimeout - (int)$elapsed ) );
- // If each scoped timeout is for less than one second, we end up
- // restoring the original timeout without any decrease in value.
- // Thus web scripts in an infinite loop can run forever unless we
- // take some measures to prevent this. Track total time and calls.
- self::$totalElapsed += $elapsed;
- --self::$stackDepth;
- }
- }
-}
-
-/**
- * Store a file into the backend from a file on the file system.
- * Parameters similar to FileBackendStore::storeInternal(), which include:
- * src : source path on file system
- * dst : destination storage path
- * overwrite : do nothing and pass if an identical file exists at destination
- * overwriteSame : override any existing file at destination
- */
-class StoreFileOp extends FileOp {
- protected function allowedParams() {
- return array( array( 'src', 'dst' ), array( 'overwrite', 'overwriteSame' ) );
- }
-
- protected function doPrecheck( array &$predicates ) {
- $status = Status::newGood();
- // Check if the source file exists on the file system
- if ( !is_file( $this->params['src'] ) ) {
- $status->fatal( 'backend-fail-notexists', $this->params['src'] );
- return $status;
- // Check if the source file is too big
- } elseif ( filesize( $this->params['src'] ) > $this->backend->maxFileSizeInternal() ) {
- $status->fatal( 'backend-fail-store', $this->params['src'], $this->params['dst'] );
- return $status;
- // Check if a file can be placed at the destination
- } elseif ( !$this->backend->isPathUsableInternal( $this->params['dst'] ) ) {
- $status->fatal( 'backend-fail-store', $this->params['src'], $this->params['dst'] );
- return $status;
- }
- // Check if destination file exists
- $status->merge( $this->precheckDestExistence( $predicates ) );
- if ( $status->isOK() ) {
- // Update file existence predicates
- $predicates['exists'][$this->params['dst']] = true;
- $predicates['sha1'][$this->params['dst']] = $this->sourceSha1;
- }
- return $status; // safe to call attempt()
- }
-
- protected function doAttempt() {
- $status = Status::newGood();
- // Store the file at the destination
- if ( !$this->destSameAsSource ) {
- $status->merge( $this->backend->storeInternal( $this->params ) );
- }
- return $status;
- }
-
- protected function getSourceSha1Base36() {
- wfSuppressWarnings();
- $hash = sha1_file( $this->params['src'] );
- wfRestoreWarnings();
- if ( $hash !== false ) {
- $hash = wfBaseConvert( $hash, 16, 36, 31 );
- }
- return $hash;
- }
-
- public function storagePathsChanged() {
- return array( $this->params['dst'] );
- }
-}
-
-/**
- * Create a file in the backend with the given content.
- * Parameters similar to FileBackendStore::createInternal(), which include:
- * content : the raw file contents
- * dst : destination storage path
- * overwrite : do nothing and pass if an identical file exists at destination
- * overwriteSame : override any existing file at destination
- */
-class CreateFileOp extends FileOp {
- protected function allowedParams() {
- return array( array( 'content', 'dst' ), array( 'overwrite', 'overwriteSame' ) );
- }
-
- protected function doPrecheck( array &$predicates ) {
- $status = Status::newGood();
- // Check if the source data is too big
- if ( strlen( $this->getParam( 'content' ) ) > $this->backend->maxFileSizeInternal() ) {
- $status->fatal( 'backend-fail-create', $this->params['dst'] );
- return $status;
- // Check if a file can be placed at the destination
- } elseif ( !$this->backend->isPathUsableInternal( $this->params['dst'] ) ) {
- $status->fatal( 'backend-fail-create', $this->params['dst'] );
- return $status;
- }
- // Check if destination file exists
- $status->merge( $this->precheckDestExistence( $predicates ) );
- if ( $status->isOK() ) {
- // Update file existence predicates
- $predicates['exists'][$this->params['dst']] = true;
- $predicates['sha1'][$this->params['dst']] = $this->sourceSha1;
- }
- return $status; // safe to call attempt()
- }
-
- protected function doAttempt() {
- $status = Status::newGood();
- // Create the file at the destination
- if ( !$this->destSameAsSource ) {
- $status->merge( $this->backend->createInternal( $this->params ) );
- }
- return $status;
- }
-
- protected function getSourceSha1Base36() {
- return wfBaseConvert( sha1( $this->params['content'] ), 16, 36, 31 );
- }
-
- public function storagePathsChanged() {
- return array( $this->params['dst'] );
- }
-}
-
-/**
- * Copy a file from one storage path to another in the backend.
- * Parameters similar to FileBackendStore::copyInternal(), which include:
- * src : source storage path
- * dst : destination storage path
- * overwrite : do nothing and pass if an identical file exists at destination
- * overwriteSame : override any existing file at destination
- */
-class CopyFileOp extends FileOp {
- protected function allowedParams() {
- return array( array( 'src', 'dst' ), array( 'overwrite', 'overwriteSame' ) );
- }
-
- protected function doPrecheck( array &$predicates ) {
- $status = Status::newGood();
- // Check if the source file exists
- if ( !$this->fileExists( $this->params['src'], $predicates ) ) {
- $status->fatal( 'backend-fail-notexists', $this->params['src'] );
- return $status;
- // Check if a file can be placed at the destination
- } elseif ( !$this->backend->isPathUsableInternal( $this->params['dst'] ) ) {
- $status->fatal( 'backend-fail-copy', $this->params['src'], $this->params['dst'] );
- return $status;
- }
- // Check if destination file exists
- $status->merge( $this->precheckDestExistence( $predicates ) );
- if ( $status->isOK() ) {
- // Update file existence predicates
- $predicates['exists'][$this->params['dst']] = true;
- $predicates['sha1'][$this->params['dst']] = $this->sourceSha1;
- }
- return $status; // safe to call attempt()
- }
-
- protected function doAttempt() {
- $status = Status::newGood();
- // Do nothing if the src/dst paths are the same
- if ( $this->params['src'] !== $this->params['dst'] ) {
- // Copy the file into the destination
- if ( !$this->destSameAsSource ) {
- $status->merge( $this->backend->copyInternal( $this->params ) );
- }
- }
- return $status;
- }
-
- public function storagePathsRead() {
- return array( $this->params['src'] );
- }
-
- public function storagePathsChanged() {
- return array( $this->params['dst'] );
- }
-}
-
-/**
- * Move a file from one storage path to another in the backend.
- * Parameters similar to FileBackendStore::moveInternal(), which include:
- * src : source storage path
- * dst : destination storage path
- * overwrite : do nothing and pass if an identical file exists at destination
- * overwriteSame : override any existing file at destination
- */
-class MoveFileOp extends FileOp {
- protected function allowedParams() {
- return array( array( 'src', 'dst' ), array( 'overwrite', 'overwriteSame' ) );
- }
-
- protected function doPrecheck( array &$predicates ) {
- $status = Status::newGood();
- // Check if the source file exists
- if ( !$this->fileExists( $this->params['src'], $predicates ) ) {
- $status->fatal( 'backend-fail-notexists', $this->params['src'] );
- return $status;
- // Check if a file can be placed at the destination
- } elseif ( !$this->backend->isPathUsableInternal( $this->params['dst'] ) ) {
- $status->fatal( 'backend-fail-move', $this->params['src'], $this->params['dst'] );
- return $status;
- }
- // Check if destination file exists
- $status->merge( $this->precheckDestExistence( $predicates ) );
- if ( $status->isOK() ) {
- // Update file existence predicates
- $predicates['exists'][$this->params['src']] = false;
- $predicates['sha1'][$this->params['src']] = false;
- $predicates['exists'][$this->params['dst']] = true;
- $predicates['sha1'][$this->params['dst']] = $this->sourceSha1;
- }
- return $status; // safe to call attempt()
- }
-
- protected function doAttempt() {
- $status = Status::newGood();
- // Do nothing if the src/dst paths are the same
- if ( $this->params['src'] !== $this->params['dst'] ) {
- if ( !$this->destSameAsSource ) {
- // Move the file into the destination
- $status->merge( $this->backend->moveInternal( $this->params ) );
- } else {
- // Just delete source as the destination needs no changes
- $params = array( 'src' => $this->params['src'] );
- $status->merge( $this->backend->deleteInternal( $params ) );
- }
- }
- return $status;
- }
-
- public function storagePathsRead() {
- return array( $this->params['src'] );
- }
-
- public function storagePathsChanged() {
- return array( $this->params['dst'] );
- }
-}
-
-/**
- * Delete a file at the given storage path from the backend.
- * Parameters similar to FileBackendStore::deleteInternal(), which include:
- * src : source storage path
- * ignoreMissingSource : don't return an error if the file does not exist
- */
-class DeleteFileOp extends FileOp {
- protected function allowedParams() {
- return array( array( 'src' ), array( 'ignoreMissingSource' ) );
- }
-
- protected $needsDelete = true;
-
- protected function doPrecheck( array &$predicates ) {
- $status = Status::newGood();
- // Check if the source file exists
- if ( !$this->fileExists( $this->params['src'], $predicates ) ) {
- if ( !$this->getParam( 'ignoreMissingSource' ) ) {
- $status->fatal( 'backend-fail-notexists', $this->params['src'] );
- return $status;
- }
- $this->needsDelete = false;
- }
- // Update file existence predicates
- $predicates['exists'][$this->params['src']] = false;
- $predicates['sha1'][$this->params['src']] = false;
- return $status; // safe to call attempt()
- }
-
- protected function doAttempt() {
- $status = Status::newGood();
- if ( $this->needsDelete ) {
- // Delete the source file
- $status->merge( $this->backend->deleteInternal( $this->params ) );
- }
- return $status;
- }
-
- public function storagePathsChanged() {
- return array( $this->params['src'] );
- }
-}
-
-/**
- * Placeholder operation that has no params and does nothing
- */
-class NullFileOp extends FileOp {}
diff --git a/includes/filerepo/backend/SwiftFileBackend.php b/includes/filerepo/backend/SwiftFileBackend.php
deleted file mode 100644
index a287f488..00000000
--- a/includes/filerepo/backend/SwiftFileBackend.php
+++ /dev/null
@@ -1,877 +0,0 @@
-<?php
-/**
- * @file
- * @ingroup FileBackend
- * @author Russ Nelson
- * @author Aaron Schulz
- */
-
-/**
- * Class for an OpenStack Swift based file backend.
- *
- * This requires the SwiftCloudFiles MediaWiki extension, which includes
- * the php-cloudfiles library (https://github.com/rackspace/php-cloudfiles).
- * php-cloudfiles requires the curl, fileinfo, and mb_string PHP extensions.
- *
- * Status messages should avoid mentioning the Swift account name.
- * Likewise, error suppression should be used to avoid path disclosure.
- *
- * @ingroup FileBackend
- * @since 1.19
- */
-class SwiftFileBackend extends FileBackendStore {
- /** @var CF_Authentication */
- protected $auth; // Swift authentication handler
- protected $authTTL; // integer seconds
- protected $swiftAnonUser; // string; username to handle unauthenticated requests
- protected $maxContCacheSize = 100; // integer; max containers with entries
-
- /** @var CF_Connection */
- protected $conn; // Swift connection handle
- protected $connStarted = 0; // integer UNIX timestamp
- protected $connContainers = array(); // container object cache
-
- /**
- * @see FileBackendStore::__construct()
- * Additional $config params include:
- * swiftAuthUrl : Swift authentication server URL
- * swiftUser : Swift user used by MediaWiki (account:username)
- * swiftKey : Swift authentication key for the above user
- * swiftAuthTTL : Swift authentication TTL (seconds)
- * swiftAnonUser : Swift user used for end-user requests (account:username)
- * shardViaHashLevels : Map of container names to sharding config with:
- * 'base' : base of hash characters, 16 or 36
- * 'levels' : the number of hash levels (and digits)
- * 'repeat' : hash subdirectories are prefixed with all the
- * parent hash directory names (e.g. "a/ab/abc")
- */
- public function __construct( array $config ) {
- parent::__construct( $config );
- // Required settings
- $this->auth = new CF_Authentication(
- $config['swiftUser'],
- $config['swiftKey'],
- null, // account; unused
- $config['swiftAuthUrl']
- );
- // Optional settings
- $this->authTTL = isset( $config['swiftAuthTTL'] )
- ? $config['swiftAuthTTL']
- : 120; // some sane number
- $this->swiftAnonUser = isset( $config['swiftAnonUser'] )
- ? $config['swiftAnonUser']
- : '';
- $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
- ? $config['shardViaHashLevels']
- : '';
- }
-
- /**
- * @see FileBackendStore::resolveContainerPath()
- */
- protected function resolveContainerPath( $container, $relStoragePath ) {
- if ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
- return null; // too long for Swift
- }
- return $relStoragePath;
- }
-
- /**
- * @see FileBackendStore::isPathUsableInternal()
- */
- public function isPathUsableInternal( $storagePath ) {
- list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
- if ( $rel === null ) {
- return false; // invalid
- }
-
- try {
- $this->getContainer( $container );
- return true; // container exists
- } catch ( NoSuchContainerException $e ) {
- } catch ( InvalidResponseException $e ) {
- } catch ( Exception $e ) { // some other exception?
- $this->logException( $e, __METHOD__, array( 'path' => $storagePath ) );
- }
-
- return false;
- }
-
- /**
- * @see FileBackendStore::doCreateInternal()
- */
- protected function doCreateInternal( array $params ) {
- $status = Status::newGood();
-
- list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
- if ( $dstRel === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
- return $status;
- }
-
- // (a) Check the destination container and object
- try {
- $dContObj = $this->getContainer( $dstCont );
- if ( empty( $params['overwrite'] ) &&
- $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
- {
- $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
- return $status;
- }
- } catch ( NoSuchContainerException $e ) {
- $status->fatal( 'backend-fail-create', $params['dst'] );
- return $status;
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- return $status;
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- return $status;
- }
-
- // (b) Get a SHA-1 hash of the object
- $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
-
- // (c) Actually create the object
- try {
- // Create a fresh CF_Object with no fields preloaded.
- // We don't want to preserve headers, metadata, and such.
- $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
- // Note: metadata keys stored as [Upper case char][[Lower case char]...]
- $obj->metadata = array( 'Sha1base36' => $sha1Hash );
- // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
- // The MD5 here will be checked within Swift against its own MD5.
- $obj->set_etag( md5( $params['content'] ) );
- // Use the same content type as StreamFile for security
- $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
- // Actually write the object in Swift
- $obj->write( $params['content'] );
- } catch ( BadContentTypeException $e ) {
- $status->fatal( 'backend-fail-contenttype', $params['dst'] );
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doStoreInternal()
- */
- protected function doStoreInternal( array $params ) {
- $status = Status::newGood();
-
- list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
- if ( $dstRel === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
- return $status;
- }
-
- // (a) Check the destination container and object
- try {
- $dContObj = $this->getContainer( $dstCont );
- if ( empty( $params['overwrite'] ) &&
- $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
- {
- $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
- return $status;
- }
- } catch ( NoSuchContainerException $e ) {
- $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
- return $status;
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- return $status;
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- return $status;
- }
-
- // (b) Get a SHA-1 hash of the object
- $sha1Hash = sha1_file( $params['src'] );
- if ( $sha1Hash === false ) { // source doesn't exist?
- $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
- return $status;
- }
- $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
-
- // (c) Actually store the object
- try {
- // Create a fresh CF_Object with no fields preloaded.
- // We don't want to preserve headers, metadata, and such.
- $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
- // Note: metadata keys stored as [Upper case char][[Lower case char]...]
- $obj->metadata = array( 'Sha1base36' => $sha1Hash );
- // The MD5 here will be checked within Swift against its own MD5.
- $obj->set_etag( md5_file( $params['src'] ) );
- // Use the same content type as StreamFile for security
- $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
- // Actually write the object in Swift
- $obj->load_from_filename( $params['src'], True ); // calls $obj->write()
- } catch ( BadContentTypeException $e ) {
- $status->fatal( 'backend-fail-contenttype', $params['dst'] );
- } catch ( IOException $e ) {
- $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doCopyInternal()
- */
- protected function doCopyInternal( array $params ) {
- $status = Status::newGood();
-
- list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
- if ( $srcRel === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['src'] );
- return $status;
- }
-
- list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
- if ( $dstRel === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
- return $status;
- }
-
- // (a) Check the source/destination containers and destination object
- try {
- $sContObj = $this->getContainer( $srcCont );
- $dContObj = $this->getContainer( $dstCont );
- if ( empty( $params['overwrite'] ) &&
- $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
- {
- $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
- return $status;
- }
- } catch ( NoSuchContainerException $e ) {
- $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
- return $status;
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- return $status;
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- return $status;
- }
-
- // (b) Actually copy the file to the destination
- try {
- $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
- } catch ( NoSuchObjectException $e ) { // source object does not exist
- $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doDeleteInternal()
- */
- protected function doDeleteInternal( array $params ) {
- $status = Status::newGood();
-
- list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
- if ( $srcRel === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['src'] );
- return $status;
- }
-
- try {
- $sContObj = $this->getContainer( $srcCont );
- $sContObj->delete_object( $srcRel );
- } catch ( NoSuchContainerException $e ) {
- $status->fatal( 'backend-fail-delete', $params['src'] );
- } catch ( NoSuchObjectException $e ) {
- if ( empty( $params['ignoreMissingSource'] ) ) {
- $status->fatal( 'backend-fail-delete', $params['src'] );
- }
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doPrepareInternal()
- */
- protected function doPrepareInternal( $fullCont, $dir, array $params ) {
- $status = Status::newGood();
-
- // (a) Check if container already exists
- try {
- $contObj = $this->getContainer( $fullCont );
- // NoSuchContainerException not thrown: container must exist
- return $status; // already exists
- } catch ( NoSuchContainerException $e ) {
- // NoSuchContainerException thrown: container does not exist
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- return $status;
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- return $status;
- }
-
- // (b) Create container as needed
- try {
- $contObj = $this->createContainer( $fullCont );
- if ( $this->swiftAnonUser != '' ) {
- // Make container public to end-users...
- $status->merge( $this->setContainerAccess(
- $contObj,
- array( $this->auth->username, $this->swiftAnonUser ), // read
- array( $this->auth->username ) // write
- ) );
- }
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- return $status;
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- return $status;
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doSecureInternal()
- */
- protected function doSecureInternal( $fullCont, $dir, array $params ) {
- $status = Status::newGood();
-
- if ( $this->swiftAnonUser != '' ) {
- // Restrict container from end-users...
- try {
- // doPrepareInternal() should have been called,
- // so the Swift container should already exist...
- $contObj = $this->getContainer( $fullCont ); // normally a cache hit
- // NoSuchContainerException not thrown: container must exist
- if ( !isset( $contObj->mw_wasSecured ) ) {
- $status->merge( $this->setContainerAccess(
- $contObj,
- array( $this->auth->username ), // read
- array( $this->auth->username ) // write
- ) );
- // @TODO: when php-cloudfiles supports container
- // metadata, we can make use of that to avoid RTTs
- $contObj->mw_wasSecured = true; // avoid useless RTTs
- }
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- }
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doCleanInternal()
- */
- protected function doCleanInternal( $fullCont, $dir, array $params ) {
- $status = Status::newGood();
-
- // Only containers themselves can be removed, all else is virtual
- if ( $dir != '' ) {
- return $status; // nothing to do
- }
-
- // (a) Check the container
- try {
- $contObj = $this->getContainer( $fullCont, true );
- } catch ( NoSuchContainerException $e ) {
- return $status; // ok, nothing to do
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- return $status;
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- return $status;
- }
-
- // (b) Delete the container if empty
- if ( $contObj->object_count == 0 ) {
- try {
- $this->deleteContainer( $fullCont );
- } catch ( NoSuchContainerException $e ) {
- return $status; // race?
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- return $status;
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-internal', $this->name );
- $this->logException( $e, __METHOD__, $params );
- return $status;
- }
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::doFileExists()
- */
- protected function doGetFileStat( array $params ) {
- list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
- if ( $srcRel === null ) {
- return false; // invalid storage path
- }
-
- $stat = false;
- try {
- $contObj = $this->getContainer( $srcCont );
- $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
- $this->addMissingMetadata( $srcObj, $params['src'] );
- $stat = array(
- // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
- 'mtime' => wfTimestamp( TS_MW, $srcObj->last_modified ),
- 'size' => $srcObj->content_length,
- 'sha1' => $srcObj->metadata['Sha1base36']
- );
- } catch ( NoSuchContainerException $e ) {
- } catch ( NoSuchObjectException $e ) {
- } catch ( InvalidResponseException $e ) {
- $stat = null;
- } catch ( Exception $e ) { // some other exception?
- $stat = null;
- $this->logException( $e, __METHOD__, $params );
- }
-
- return $stat;
- }
-
- /**
- * Fill in any missing object metadata and save it to Swift
- *
- * @param $obj CF_Object
- * @param $path string Storage path to object
- * @return bool Success
- * @throws Exception cloudfiles exceptions
- */
- protected function addMissingMetadata( CF_Object $obj, $path ) {
- if ( isset( $obj->metadata['Sha1base36'] ) ) {
- return true; // nothing to do
- }
- $status = Status::newGood();
- $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
- if ( $status->isOK() ) {
- $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
- if ( $tmpFile ) {
- $hash = $tmpFile->getSha1Base36();
- if ( $hash !== false ) {
- $obj->metadata['Sha1base36'] = $hash;
- $obj->sync_metadata(); // save to Swift
- return true; // success
- }
- }
- }
- $obj->metadata['Sha1base36'] = false;
- return false; // failed
- }
-
- /**
- * @see FileBackend::getFileContents()
- */
- public function getFileContents( array $params ) {
- list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
- if ( $srcRel === null ) {
- return false; // invalid storage path
- }
-
- if ( !$this->fileExists( $params ) ) {
- return null;
- }
-
- $data = false;
- try {
- $sContObj = $this->getContainer( $srcCont );
- $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD request
- $data = $obj->read( $this->headersFromParams( $params ) );
- } catch ( NoSuchContainerException $e ) {
- } catch ( InvalidResponseException $e ) {
- } catch ( Exception $e ) { // some other exception?
- $this->logException( $e, __METHOD__, $params );
- }
-
- return $data;
- }
-
- /**
- * @see FileBackendStore::getFileListInternal()
- */
- public function getFileListInternal( $fullCont, $dir, array $params ) {
- return new SwiftFileBackendFileList( $this, $fullCont, $dir );
- }
-
- /**
- * Do not call this function outside of SwiftFileBackendFileList
- *
- * @param $fullCont string Resolved container name
- * @param $dir string Resolved storage directory with no trailing slash
- * @param $after string Storage path of file to list items after
- * @param $limit integer Max number of items to list
- * @return Array
- */
- public function getFileListPageInternal( $fullCont, $dir, $after, $limit ) {
- $files = array();
-
- try {
- $container = $this->getContainer( $fullCont );
- $prefix = ( $dir == '' ) ? null : "{$dir}/";
- $files = $container->list_objects( $limit, $after, $prefix );
- } catch ( NoSuchContainerException $e ) {
- } catch ( NoSuchObjectException $e ) {
- } catch ( InvalidResponseException $e ) {
- } catch ( Exception $e ) { // some other exception?
- $this->logException( $e, __METHOD__, array( 'cont' => $fullCont, 'dir' => $dir ) );
- }
-
- return $files;
- }
-
- /**
- * @see FileBackendStore::doGetFileSha1base36()
- */
- public function doGetFileSha1base36( array $params ) {
- $stat = $this->getFileStat( $params );
- if ( $stat ) {
- return $stat['sha1'];
- } else {
- return false;
- }
- }
-
- /**
- * @see FileBackendStore::doStreamFile()
- */
- protected function doStreamFile( array $params ) {
- $status = Status::newGood();
-
- list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
- if ( $srcRel === null ) {
- $status->fatal( 'backend-fail-invalidpath', $params['src'] );
- }
-
- try {
- $cont = $this->getContainer( $srcCont );
- } catch ( NoSuchContainerException $e ) {
- $status->fatal( 'backend-fail-stream', $params['src'] );
- return $status;
- } catch ( InvalidResponseException $e ) {
- $status->fatal( 'backend-fail-connect', $this->name );
- return $status;
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-stream', $params['src'] );
- $this->logException( $e, __METHOD__, $params );
- return $status;
- }
-
- try {
- $output = fopen( 'php://output', 'wb' );
- $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD request
- $obj->stream( $output, $this->headersFromParams( $params ) );
- } catch ( InvalidResponseException $e ) { // 404? connection problem?
- $status->fatal( 'backend-fail-stream', $params['src'] );
- } catch ( Exception $e ) { // some other exception?
- $status->fatal( 'backend-fail-stream', $params['src'] );
- $this->logException( $e, __METHOD__, $params );
- }
-
- return $status;
- }
-
- /**
- * @see FileBackendStore::getLocalCopy()
- */
- public function getLocalCopy( array $params ) {
- list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
- if ( $srcRel === null ) {
- return null;
- }
-
- if ( !$this->fileExists( $params ) ) {
- return null;
- }
-
- $tmpFile = null;
- try {
- $sContObj = $this->getContainer( $srcCont );
- $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
- // Get source file extension
- $ext = FileBackend::extensionFromPath( $srcRel );
- // Create a new temporary file...
- $tmpFile = TempFSFile::factory( wfBaseName( $srcRel ) . '_', $ext );
- if ( $tmpFile ) {
- $handle = fopen( $tmpFile->getPath(), 'wb' );
- if ( $handle ) {
- $obj->stream( $handle, $this->headersFromParams( $params ) );
- fclose( $handle );
- } else {
- $tmpFile = null; // couldn't open temp file
- }
- }
- } catch ( NoSuchContainerException $e ) {
- $tmpFile = null;
- } catch ( InvalidResponseException $e ) {
- $tmpFile = null;
- } catch ( Exception $e ) { // some other exception?
- $tmpFile = null;
- $this->logException( $e, __METHOD__, $params );
- }
-
- return $tmpFile;
- }
-
- /**
- * Get headers to send to Swift when reading a file based
- * on a FileBackend params array, e.g. that of getLocalCopy().
- * $params is currently only checked for a 'latest' flag.
- *
- * @param $params Array
- * @return Array
- */
- protected function headersFromParams( array $params ) {
- $hdrs = array();
- if ( !empty( $params['latest'] ) ) {
- $hdrs[] = 'X-Newest: true';
- }
- return $hdrs;
- }
-
- /**
- * Set read/write permissions for a Swift container
- *
- * @param $contObj CF_Container Swift container
- * @param $readGrps Array Swift users who can read (account:user)
- * @param $writeGrps Array Swift users who can write (account:user)
- * @return Status
- */
- protected function setContainerAccess(
- CF_Container $contObj, array $readGrps, array $writeGrps
- ) {
- $creds = $contObj->cfs_auth->export_credentials();
-
- $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
-
- // Note: 10 second timeout consistent with php-cloudfiles
- $req = new CurlHttpRequest( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
- $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
- $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
- $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
-
- return $req->execute(); // should return 204
- }
-
- /**
- * Get a connection to the Swift proxy
- *
- * @return CF_Connection|false
- * @throws InvalidResponseException
- */
- protected function getConnection() {
- if ( $this->conn === false ) {
- throw new InvalidResponseException; // failed last attempt
- }
- // Session keys expire after a while, so we renew them periodically
- if ( $this->conn && ( time() - $this->connStarted ) > $this->authTTL ) {
- $this->conn->close(); // close active cURL connections
- $this->conn = null;
- }
- // Authenticate with proxy and get a session key...
- if ( $this->conn === null ) {
- $this->connContainers = array();
- try {
- $this->auth->authenticate();
- $this->conn = new CF_Connection( $this->auth );
- $this->connStarted = time();
- } catch ( AuthenticationException $e ) {
- $this->conn = false; // don't keep re-trying
- } catch ( InvalidResponseException $e ) {
- $this->conn = false; // don't keep re-trying
- }
- }
- if ( !$this->conn ) {
- throw new InvalidResponseException; // auth/connection problem
- }
- return $this->conn;
- }
-
- /**
- * @see FileBackendStore::doClearCache()
- */
- protected function doClearCache( array $paths = null ) {
- $this->connContainers = array(); // clear container object cache
- }
-
- /**
- * Get a Swift container object, possibly from process cache.
- * Use $reCache if the file count or byte count is needed.
- *
- * @param $container string Container name
- * @param $reCache bool Refresh the process cache
- * @return CF_Container
- */
- protected function getContainer( $container, $reCache = false ) {
- $conn = $this->getConnection(); // Swift proxy connection
- if ( $reCache ) {
- unset( $this->connContainers[$container] ); // purge cache
- }
- if ( !isset( $this->connContainers[$container] ) ) {
- $contObj = $conn->get_container( $container );
- // NoSuchContainerException not thrown: container must exist
- if ( count( $this->connContainers ) >= $this->maxContCacheSize ) { // trim cache?
- reset( $this->connContainers );
- $key = key( $this->connContainers );
- unset( $this->connContainers[$key] );
- }
- $this->connContainers[$container] = $contObj; // cache it
- }
- return $this->connContainers[$container];
- }
-
- /**
- * Create a Swift container
- *
- * @param $container string Container name
- * @return CF_Container
- */
- protected function createContainer( $container ) {
- $conn = $this->getConnection(); // Swift proxy connection
- $contObj = $conn->create_container( $container );
- $this->connContainers[$container] = $contObj; // cache it
- return $contObj;
- }
-
- /**
- * Delete a Swift container
- *
- * @param $container string Container name
- * @return void
- */
- protected function deleteContainer( $container ) {
- $conn = $this->getConnection(); // Swift proxy connection
- $conn->delete_container( $container );
- unset( $this->connContainers[$container] ); // purge cache
- }
-
- /**
- * Log an unexpected exception for this backend
- *
- * @param $e Exception
- * @param $func string
- * @param $params Array
- * @return void
- */
- protected function logException( Exception $e, $func, array $params ) {
- wfDebugLog( 'SwiftBackend',
- get_class( $e ) . " in '{$func}' (given '" . serialize( $params ) . "')" .
- ( $e instanceof InvalidResponseException
- ? ": {$e->getMessage()}"
- : ""
- )
- );
- }
-}
-
-/**
- * SwiftFileBackend helper class to page through object listings.
- * Swift also has a listing limit of 10,000 objects for sanity.
- * Do not use this class from places outside SwiftFileBackend.
- *
- * @ingroup FileBackend
- */
-class SwiftFileBackendFileList implements Iterator {
- /** @var Array */
- protected $bufferIter = array();
- protected $bufferAfter = null; // string; list items *after* this path
- protected $pos = 0; // integer
-
- /** @var SwiftFileBackend */
- protected $backend;
- protected $container; //
- protected $dir; // string storage directory
- protected $suffixStart; // integer
-
- const PAGE_SIZE = 5000; // file listing buffer size
-
- /**
- * @param $backend SwiftFileBackend
- * @param $fullCont string Resolved container name
- * @param $dir string Resolved directory relative to container
- */
- public function __construct( SwiftFileBackend $backend, $fullCont, $dir ) {
- $this->backend = $backend;
- $this->container = $fullCont;
- $this->dir = $dir;
- if ( substr( $this->dir, -1 ) === '/' ) {
- $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
- }
- if ( $this->dir == '' ) { // whole container
- $this->suffixStart = 0;
- } else { // dir within container
- $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
- }
- }
-
- public function current() {
- return substr( current( $this->bufferIter ), $this->suffixStart );
- }
-
- public function key() {
- return $this->pos;
- }
-
- public function next() {
- // Advance to the next file in the page
- next( $this->bufferIter );
- ++$this->pos;
- // Check if there are no files left in this page and
- // advance to the next page if this page was not empty.
- if ( !$this->valid() && count( $this->bufferIter ) ) {
- $this->bufferAfter = end( $this->bufferIter );
- $this->bufferIter = $this->backend->getFileListPageInternal(
- $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE
- );
- }
- }
-
- public function rewind() {
- $this->pos = 0;
- $this->bufferAfter = null;
- $this->bufferIter = $this->backend->getFileListPageInternal(
- $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE
- );
- }
-
- public function valid() {
- return ( current( $this->bufferIter ) !== false ); // no paths can have this value
- }
-}
diff --git a/includes/filerepo/backend/TempFSFile.php b/includes/filerepo/backend/TempFSFile.php
deleted file mode 100644
index 7843d6cd..00000000
--- a/includes/filerepo/backend/TempFSFile.php
+++ /dev/null
@@ -1,92 +0,0 @@
-<?php
-/**
- * @file
- * @ingroup FileBackend
- */
-
-/**
- * This class is used to hold the location and do limited manipulation
- * of files stored temporarily (usually this will be $wgTmpDirectory)
- *
- * @ingroup FileBackend
- */
-class TempFSFile extends FSFile {
- protected $canDelete = false; // bool; garbage collect the temp file
-
- /** @var Array of active temp files to purge on shutdown */
- protected static $instances = array();
-
- /**
- * Make a new temporary file on the file system.
- * Temporary files may be purged when the file object falls out of scope.
- *
- * @param $prefix string
- * @param $extension string
- * @return TempFSFile|null
- */
- public static function factory( $prefix, $extension = '' ) {
- $base = wfTempDir() . '/' . $prefix . dechex( mt_rand( 0, 99999999 ) );
- $ext = ( $extension != '' ) ? ".{$extension}" : "";
- for ( $attempt = 1; true; $attempt++ ) {
- $path = "{$base}-{$attempt}{$ext}";
- wfSuppressWarnings();
- $newFileHandle = fopen( $path, 'x' );
- wfRestoreWarnings();
- if ( $newFileHandle ) {
- fclose( $newFileHandle );
- break; // got it
- }
- if ( $attempt >= 15 ) {
- return null; // give up
- }
- }
- $tmpFile = new self( $path );
- $tmpFile->canDelete = true; // safely instantiated
- return $tmpFile;
- }
-
- /**
- * Purge this file off the file system
- *
- * @return bool Success
- */
- public function purge() {
- $this->canDelete = false; // done
- wfSuppressWarnings();
- $ok = unlink( $this->path );
- wfRestoreWarnings();
- return $ok;
- }
-
- /**
- * Clean up the temporary file only after an object goes out of scope
- *
- * @param $object Object
- * @return void
- */
- public function bind( $object ) {
- if ( is_object( $object ) ) {
- $object->tempFSFileReferences[] = $this;
- }
- }
-
- /**
- * Set flag to not clean up after the temporary file
- *
- * @return void
- */
- public function preserve() {
- $this->canDelete = false;
- }
-
- /**
- * Cleans up after the temporary file by deleting it
- */
- function __destruct() {
- if ( $this->canDelete ) {
- wfSuppressWarnings();
- unlink( $this->path );
- wfRestoreWarnings();
- }
- }
-}
diff --git a/includes/filerepo/backend/lockmanager/DBLockManager.php b/includes/filerepo/backend/lockmanager/DBLockManager.php
deleted file mode 100644
index 045056ea..00000000
--- a/includes/filerepo/backend/lockmanager/DBLockManager.php
+++ /dev/null
@@ -1,469 +0,0 @@
-<?php
-
-/**
- * Version of LockManager based on using DB table locks.
- * This is meant for multi-wiki systems that may share files.
- * All locks are blocking, so it might be useful to set a small
- * lock-wait timeout via server config to curtail deadlocks.
- *
- * All lock requests for a resource, identified by a hash string, will map
- * to one bucket. Each bucket maps to one or several peer DBs, each on their
- * own server, all having the filelocks.sql tables (with row-level locking).
- * A majority of peer DBs must agree for a lock to be acquired.
- *
- * Caching is used to avoid hitting servers that are down.
- *
- * @ingroup LockManager
- * @since 1.19
- */
-class DBLockManager extends LockManager {
- /** @var Array Map of DB names to server config */
- protected $dbServers; // (DB name => server config array)
- /** @var Array Map of bucket indexes to peer DB lists */
- protected $dbsByBucket; // (bucket index => (ldb1, ldb2, ...))
- /** @var BagOStuff */
- protected $statusCache;
-
- protected $lockExpiry; // integer number of seconds
- protected $safeDelay; // integer number of seconds
-
- protected $session = 0; // random integer
- /** @var Array Map Database connections (DB name => Database) */
- protected $conns = array();
-
- /**
- * Construct a new instance from configuration.
- *
- * $config paramaters include:
- * 'dbServers' : Associative array of DB names to server configuration.
- * Configuration is an associative array that includes:
- * 'host' - DB server name
- * 'dbname' - DB name
- * 'type' - DB type (mysql,postgres,...)
- * 'user' - DB user
- * 'password' - DB user password
- * 'tablePrefix' - DB table prefix
- * 'flags' - DB flags (see DatabaseBase)
- * 'dbsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
- * each having an odd-numbered list of DB names (peers) as values.
- * Any DB named 'localDBMaster' will automatically use the DB master
- * settings for this wiki (without the need for a dbServers entry).
- * 'lockExpiry' : Lock timeout (seconds) for dropped connections. [optional]
- * This tells the DB server how long to wait before assuming
- * connection failure and releasing all the locks for a session.
- *
- * @param Array $config
- */
- public function __construct( array $config ) {
- $this->dbServers = isset( $config['dbServers'] )
- ? $config['dbServers']
- : array(); // likely just using 'localDBMaster'
- // Sanitize dbsByBucket config to prevent PHP errors
- $this->dbsByBucket = array_filter( $config['dbsByBucket'], 'is_array' );
- $this->dbsByBucket = array_values( $this->dbsByBucket ); // consecutive
-
- if ( isset( $config['lockExpiry'] ) ) {
- $this->lockExpiry = $config['lockExpiry'];
- } else {
- $met = ini_get( 'max_execution_time' );
- $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
- }
- $this->safeDelay = ( $this->lockExpiry <= 0 )
- ? 60 // pick a safe-ish number to match DB timeout default
- : $this->lockExpiry; // cover worst case
-
- foreach ( $this->dbsByBucket as $bucket ) {
- if ( count( $bucket ) > 1 ) {
- // Tracks peers that couldn't be queried recently to avoid lengthy
- // connection timeouts. This is useless if each bucket has one peer.
- $this->statusCache = wfGetMainCache();
- break;
- }
- }
-
- $this->session = '';
- for ( $i = 0; $i < 5; $i++ ) {
- $this->session .= mt_rand( 0, 2147483647 );
- }
- $this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
- }
-
- /**
- * @see LockManager::doLock()
- */
- protected function doLock( array $paths, $type ) {
- $status = Status::newGood();
-
- $pathsToLock = array();
- // Get locks that need to be acquired (buckets => locks)...
- foreach ( $paths as $path ) {
- if ( isset( $this->locksHeld[$path][$type] ) ) {
- ++$this->locksHeld[$path][$type];
- } elseif ( isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
- $this->locksHeld[$path][$type] = 1;
- } else {
- $bucket = $this->getBucketFromKey( $path );
- $pathsToLock[$bucket][] = $path;
- }
- }
-
- $lockedPaths = array(); // files locked in this attempt
- // Attempt to acquire these locks...
- foreach ( $pathsToLock as $bucket => $paths ) {
- // Try to acquire the locks for this bucket
- $res = $this->doLockingQueryAll( $bucket, $paths, $type );
- if ( $res === 'cantacquire' ) {
- // Resources already locked by another process.
- // Abort and unlock everything we just locked.
- foreach ( $paths as $path ) {
- $status->fatal( 'lockmanager-fail-acquirelock', $path );
- }
- $status->merge( $this->doUnlock( $lockedPaths, $type ) );
- return $status;
- } elseif ( $res !== true ) {
- // Couldn't contact any DBs for this bucket.
- // Abort and unlock everything we just locked.
- $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
- $status->merge( $this->doUnlock( $lockedPaths, $type ) );
- return $status;
- }
- // Record these locks as active
- foreach ( $paths as $path ) {
- $this->locksHeld[$path][$type] = 1; // locked
- }
- // Keep track of what locks were made in this attempt
- $lockedPaths = array_merge( $lockedPaths, $paths );
- }
-
- return $status;
- }
-
- /**
- * @see LockManager::doUnlock()
- */
- protected function doUnlock( array $paths, $type ) {
- $status = Status::newGood();
-
- foreach ( $paths as $path ) {
- if ( !isset( $this->locksHeld[$path] ) ) {
- $status->warning( 'lockmanager-notlocked', $path );
- } elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
- $status->warning( 'lockmanager-notlocked', $path );
- } else {
- --$this->locksHeld[$path][$type];
- if ( $this->locksHeld[$path][$type] <= 0 ) {
- unset( $this->locksHeld[$path][$type] );
- }
- if ( !count( $this->locksHeld[$path] ) ) {
- unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
- }
- }
- }
-
- // Reference count the locks held and COMMIT when zero
- if ( !count( $this->locksHeld ) ) {
- $status->merge( $this->finishLockTransactions() );
- }
-
- return $status;
- }
-
- /**
- * Get a connection to a lock DB and acquire locks on $paths.
- * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
- *
- * @param $lockDb string
- * @param $paths Array
- * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
- * @return bool Resources able to be locked
- * @throws DBError
- */
- protected function doLockingQuery( $lockDb, array $paths, $type ) {
- if ( $type == self::LOCK_EX ) { // writer locks
- $db = $this->getConnection( $lockDb );
- if ( !$db ) {
- return false; // bad config
- }
- $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
- # Build up values for INSERT clause
- $data = array();
- foreach ( $keys as $key ) {
- $data[] = array( 'fle_key' => $key );
- }
- # Wait on any existing writers and block new ones if we get in
- $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
- }
- return true;
- }
-
- /**
- * Attempt to acquire locks with the peers for a bucket.
- * This should avoid throwing any exceptions.
- *
- * @param $bucket integer
- * @param $paths Array List of resource keys to lock
- * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
- * @return bool|string One of (true, 'cantacquire', 'dberrors')
- */
- protected function doLockingQueryAll( $bucket, array $paths, $type ) {
- $yesVotes = 0; // locks made on trustable DBs
- $votesLeft = count( $this->dbsByBucket[$bucket] ); // remaining DBs
- $quorum = floor( $votesLeft/2 + 1 ); // simple majority
- // Get votes for each DB, in order, until we have enough...
- foreach ( $this->dbsByBucket[$bucket] as $lockDb ) {
- // Check that DB is not *known* to be down
- if ( $this->cacheCheckFailures( $lockDb ) ) {
- try {
- // Attempt to acquire the lock on this DB
- if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
- return 'cantacquire'; // vetoed; resource locked
- }
- ++$yesVotes; // success for this peer
- if ( $yesVotes >= $quorum ) {
- return true; // lock obtained
- }
- } catch ( DBConnectionError $e ) {
- $this->cacheRecordFailure( $lockDb );
- } catch ( DBError $e ) {
- if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
- return 'cantacquire'; // vetoed; resource locked
- }
- }
- }
- --$votesLeft;
- $votesNeeded = $quorum - $yesVotes;
- if ( $votesNeeded > $votesLeft ) {
- // In "trust cache" mode we don't have to meet the quorum
- break; // short-circuit
- }
- }
- // At this point, we must not have meet the quorum
- return 'dberrors'; // not enough votes to ensure correctness
- }
-
- /**
- * Get (or reuse) a connection to a lock DB
- *
- * @param $lockDb string
- * @return Database
- * @throws DBError
- */
- protected function getConnection( $lockDb ) {
- if ( !isset( $this->conns[$lockDb] ) ) {
- $db = null;
- if ( $lockDb === 'localDBMaster' ) {
- $lb = wfGetLBFactory()->newMainLB();
- $db = $lb->getConnection( DB_MASTER );
- } elseif ( isset( $this->dbServers[$lockDb] ) ) {
- $config = $this->dbServers[$lockDb];
- $db = DatabaseBase::factory( $config['type'], $config );
- }
- if ( !$db ) {
- return null; // config error?
- }
- $this->conns[$lockDb] = $db;
- $this->conns[$lockDb]->clearFlag( DBO_TRX );
- # If the connection drops, try to avoid letting the DB rollback
- # and release the locks before the file operations are finished.
- # This won't handle the case of DB server restarts however.
- $options = array();
- if ( $this->lockExpiry > 0 ) {
- $options['connTimeout'] = $this->lockExpiry;
- }
- $this->conns[$lockDb]->setSessionOptions( $options );
- $this->initConnection( $lockDb, $this->conns[$lockDb] );
- }
- if ( !$this->conns[$lockDb]->trxLevel() ) {
- $this->conns[$lockDb]->begin(); // start transaction
- }
- return $this->conns[$lockDb];
- }
-
- /**
- * Do additional initialization for new lock DB connection
- *
- * @param $lockDb string
- * @param $db DatabaseBase
- * @return void
- * @throws DBError
- */
- protected function initConnection( $lockDb, DatabaseBase $db ) {}
-
- /**
- * Commit all changes to lock-active databases.
- * This should avoid throwing any exceptions.
- *
- * @return Status
- */
- protected function finishLockTransactions() {
- $status = Status::newGood();
- foreach ( $this->conns as $lockDb => $db ) {
- if ( $db->trxLevel() ) { // in transaction
- try {
- $db->rollback(); // finish transaction and kill any rows
- } catch ( DBError $e ) {
- $status->fatal( 'lockmanager-fail-db-release', $lockDb );
- }
- }
- }
- return $status;
- }
-
- /**
- * Check if the last DB error for $lockDb indicates
- * that a requested resource was locked by another process.
- * This should avoid throwing any exceptions.
- *
- * @param $lockDb string
- * @return bool
- */
- protected function lastErrorIndicatesLocked( $lockDb ) {
- if ( isset( $this->conns[$lockDb] ) ) { // sanity
- $db = $this->conns[$lockDb];
- return ( $db->wasDeadlock() || $db->wasLockTimeout() );
- }
- return false;
- }
-
- /**
- * Checks if the DB has not recently had connection/query errors.
- * This just avoids wasting time on doomed connection attempts.
- *
- * @param $lockDb string
- * @return bool
- */
- protected function cacheCheckFailures( $lockDb ) {
- if ( $this->statusCache && $this->safeDelay > 0 ) {
- $path = $this->getMissKey( $lockDb );
- $misses = $this->statusCache->get( $path );
- return !$misses;
- }
- return true;
- }
-
- /**
- * Log a lock request failure to the cache
- *
- * @param $lockDb string
- * @return bool Success
- */
- protected function cacheRecordFailure( $lockDb ) {
- if ( $this->statusCache && $this->safeDelay > 0 ) {
- $path = $this->getMissKey( $lockDb );
- $misses = $this->statusCache->get( $path );
- if ( $misses ) {
- return $this->statusCache->incr( $path );
- } else {
- return $this->statusCache->add( $path, 1, $this->safeDelay );
- }
- }
- return true;
- }
-
- /**
- * Get a cache key for recent query misses for a DB
- *
- * @param $lockDb string
- * @return string
- */
- protected function getMissKey( $lockDb ) {
- return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
- }
-
- /**
- * Get the bucket for resource path.
- * This should avoid throwing any exceptions.
- *
- * @param $path string
- * @return integer
- */
- protected function getBucketFromKey( $path ) {
- $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
- return intval( base_convert( $prefix, 16, 10 ) ) % count( $this->dbsByBucket );
- }
-
- /**
- * Make sure remaining locks get cleared for sanity
- */
- function __destruct() {
- foreach ( $this->conns as $lockDb => $db ) {
- if ( $db->trxLevel() ) { // in transaction
- try {
- $db->rollback(); // finish transaction and kill any rows
- } catch ( DBError $e ) {
- // oh well
- }
- }
- $db->close();
- }
- }
-}
-
-/**
- * MySQL version of DBLockManager that supports shared locks.
- * All locks are non-blocking, which avoids deadlocks.
- *
- * @ingroup LockManager
- */
-class MySqlLockManager extends DBLockManager {
- /** @var Array Mapping of lock types to the type actually used */
- protected $lockTypeMap = array(
- self::LOCK_SH => self::LOCK_SH,
- self::LOCK_UW => self::LOCK_SH,
- self::LOCK_EX => self::LOCK_EX
- );
-
- protected function initConnection( $lockDb, DatabaseBase $db ) {
- # Let this transaction see lock rows from other transactions
- $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
- }
-
- protected function doLockingQuery( $lockDb, array $paths, $type ) {
- $db = $this->getConnection( $lockDb );
- if ( !$db ) {
- return false;
- }
- $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
- # Build up values for INSERT clause
- $data = array();
- foreach ( $keys as $key ) {
- $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
- }
- # Block new writers...
- $db->insert( 'filelocks_shared', $data, __METHOD__, array( 'IGNORE' ) );
- # Actually do the locking queries...
- if ( $type == self::LOCK_SH ) { // reader locks
- # Bail if there are any existing writers...
- $blocked = $db->selectField( 'filelocks_exclusive', '1',
- array( 'fle_key' => $keys ),
- __METHOD__
- );
- # Prospective writers that haven't yet updated filelocks_exclusive
- # will recheck filelocks_shared after doing so and bail due to our entry.
- } else { // writer locks
- $encSession = $db->addQuotes( $this->session );
- # Bail if there are any existing writers...
- # The may detect readers, but the safe check for them is below.
- # Note: if two writers come at the same time, both bail :)
- $blocked = $db->selectField( 'filelocks_shared', '1',
- array( 'fls_key' => $keys, "fls_session != $encSession" ),
- __METHOD__
- );
- if ( !$blocked ) {
- # Build up values for INSERT clause
- $data = array();
- foreach ( $keys as $key ) {
- $data[] = array( 'fle_key' => $key );
- }
- # Block new readers/writers...
- $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
- # Bail if there are any existing readers...
- $blocked = $db->selectField( 'filelocks_shared', '1',
- array( 'fls_key' => $keys, "fls_session != $encSession" ),
- __METHOD__
- );
- }
- }
- return !$blocked;
- }
-}
diff --git a/includes/filerepo/backend/lockmanager/FSLockManager.php b/includes/filerepo/backend/lockmanager/FSLockManager.php
deleted file mode 100644
index 42074fd3..00000000
--- a/includes/filerepo/backend/lockmanager/FSLockManager.php
+++ /dev/null
@@ -1,202 +0,0 @@
-<?php
-
-/**
- * Simple version of LockManager based on using FS lock files.
- * All locks are non-blocking, which avoids deadlocks.
- *
- * This should work fine for small sites running off one server.
- * Do not use this with 'lockDirectory' set to an NFS mount unless the
- * NFS client is at least version 2.6.12. Otherwise, the BSD flock()
- * locks will be ignored; see http://nfs.sourceforge.net/#section_d.
- *
- * @ingroup LockManager
- * @since 1.19
- */
-class FSLockManager extends LockManager {
- /** @var Array Mapping of lock types to the type actually used */
- protected $lockTypeMap = array(
- self::LOCK_SH => self::LOCK_SH,
- self::LOCK_UW => self::LOCK_SH,
- self::LOCK_EX => self::LOCK_EX
- );
-
- protected $lockDir; // global dir for all servers
-
- /** @var Array Map of (locked key => lock type => lock file handle) */
- protected $handles = array();
-
- /**
- * Construct a new instance from configuration.
- *
- * $config includes:
- * 'lockDirectory' : Directory containing the lock files
- *
- * @param array $config
- */
- function __construct( array $config ) {
- parent::__construct( $config );
- $this->lockDir = $config['lockDirectory'];
- }
-
- protected function doLock( array $paths, $type ) {
- $status = Status::newGood();
-
- $lockedPaths = array(); // files locked in this attempt
- foreach ( $paths as $path ) {
- $status->merge( $this->doSingleLock( $path, $type ) );
- if ( $status->isOK() ) {
- $lockedPaths[] = $path;
- } else {
- // Abort and unlock everything
- $status->merge( $this->doUnlock( $lockedPaths, $type ) );
- return $status;
- }
- }
-
- return $status;
- }
-
- protected function doUnlock( array $paths, $type ) {
- $status = Status::newGood();
-
- foreach ( $paths as $path ) {
- $status->merge( $this->doSingleUnlock( $path, $type ) );
- }
-
- return $status;
- }
-
- /**
- * Lock a single resource key
- *
- * @param $path string
- * @param $type integer
- * @return Status
- */
- protected function doSingleLock( $path, $type ) {
- $status = Status::newGood();
-
- if ( isset( $this->locksHeld[$path][$type] ) ) {
- ++$this->locksHeld[$path][$type];
- } elseif ( isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
- $this->locksHeld[$path][$type] = 1;
- } else {
- wfSuppressWarnings();
- $handle = fopen( $this->getLockPath( $path ), 'a+' );
- wfRestoreWarnings();
- if ( !$handle ) { // lock dir missing?
- wfMkdirParents( $this->lockDir );
- $handle = fopen( $this->getLockPath( $path ), 'a+' ); // try again
- }
- if ( $handle ) {
- // Either a shared or exclusive lock
- $lock = ( $type == self::LOCK_SH ) ? LOCK_SH : LOCK_EX;
- if ( flock( $handle, $lock | LOCK_NB ) ) {
- // Record this lock as active
- $this->locksHeld[$path][$type] = 1;
- $this->handles[$path][$type] = $handle;
- } else {
- fclose( $handle );
- $status->fatal( 'lockmanager-fail-acquirelock', $path );
- }
- } else {
- $status->fatal( 'lockmanager-fail-openlock', $path );
- }
- }
-
- return $status;
- }
-
- /**
- * Unlock a single resource key
- *
- * @param $path string
- * @param $type integer
- * @return Status
- */
- protected function doSingleUnlock( $path, $type ) {
- $status = Status::newGood();
-
- if ( !isset( $this->locksHeld[$path] ) ) {
- $status->warning( 'lockmanager-notlocked', $path );
- } elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
- $status->warning( 'lockmanager-notlocked', $path );
- } else {
- $handlesToClose = array();
- --$this->locksHeld[$path][$type];
- if ( $this->locksHeld[$path][$type] <= 0 ) {
- unset( $this->locksHeld[$path][$type] );
- // If a LOCK_SH comes in while we have a LOCK_EX, we don't
- // actually add a handler, so check for handler existence.
- if ( isset( $this->handles[$path][$type] ) ) {
- // Mark this handle to be unlocked and closed
- $handlesToClose[] = $this->handles[$path][$type];
- unset( $this->handles[$path][$type] );
- }
- }
- // Unlock handles to release locks and delete
- // any lock files that end up with no locks on them...
- if ( wfIsWindows() ) {
- // Windows: for any process, including this one,
- // calling unlink() on a locked file will fail
- $status->merge( $this->closeLockHandles( $path, $handlesToClose ) );
- $status->merge( $this->pruneKeyLockFiles( $path ) );
- } else {
- // Unix: unlink() can be used on files currently open by this
- // process and we must do so in order to avoid race conditions
- $status->merge( $this->pruneKeyLockFiles( $path ) );
- $status->merge( $this->closeLockHandles( $path, $handlesToClose ) );
- }
- }
-
- return $status;
- }
-
- private function closeLockHandles( $path, array $handlesToClose ) {
- $status = Status::newGood();
- foreach ( $handlesToClose as $handle ) {
- wfSuppressWarnings();
- if ( !flock( $handle, LOCK_UN ) ) {
- $status->fatal( 'lockmanager-fail-releaselock', $path );
- }
- if ( !fclose( $handle ) ) {
- $status->warning( 'lockmanager-fail-closelock', $path );
- }
- wfRestoreWarnings();
- }
- return $status;
- }
-
- private function pruneKeyLockFiles( $path ) {
- $status = Status::newGood();
- if ( !count( $this->locksHeld[$path] ) ) {
- wfSuppressWarnings();
- # No locks are held for the lock file anymore
- if ( !unlink( $this->getLockPath( $path ) ) ) {
- $status->warning( 'lockmanager-fail-deletelock', $path );
- }
- wfRestoreWarnings();
- unset( $this->locksHeld[$path] );
- unset( $this->handles[$path] );
- }
- return $status;
- }
-
- /**
- * Get the path to the lock file for a key
- * @param $path string
- * @return string
- */
- protected function getLockPath( $path ) {
- $hash = self::sha1Base36( $path );
- return "{$this->lockDir}/{$hash}.lock";
- }
-
- function __destruct() {
- // Make sure remaining locks get cleared for sanity
- foreach ( $this->locksHeld as $path => $locks ) {
- $this->doSingleUnlock( $path, self::LOCK_EX );
- $this->doSingleUnlock( $path, self::LOCK_SH );
- }
- }
-}
diff --git a/includes/filerepo/backend/lockmanager/LSLockManager.php b/includes/filerepo/backend/lockmanager/LSLockManager.php
deleted file mode 100644
index b7ac743c..00000000
--- a/includes/filerepo/backend/lockmanager/LSLockManager.php
+++ /dev/null
@@ -1,295 +0,0 @@
-<?php
-
-/**
- * Manage locks using a lock daemon server.
- *
- * Version of LockManager based on using lock daemon servers.
- * This is meant for multi-wiki systems that may share files.
- * All locks are non-blocking, which avoids deadlocks.
- *
- * All lock requests for a resource, identified by a hash string, will map
- * to one bucket. Each bucket maps to one or several peer servers, each
- * running LockServerDaemon.php, listening on a designated TCP port.
- * A majority of peers must agree for a lock to be acquired.
- *
- * @ingroup LockManager
- * @since 1.19
- */
-class LSLockManager extends LockManager {
- /** @var Array Mapping of lock types to the type actually used */
- protected $lockTypeMap = array(
- self::LOCK_SH => self::LOCK_SH,
- self::LOCK_UW => self::LOCK_SH,
- self::LOCK_EX => self::LOCK_EX
- );
-
- /** @var Array Map of server names to server config */
- protected $lockServers; // (server name => server config array)
- /** @var Array Map of bucket indexes to peer server lists */
- protected $srvsByBucket; // (bucket index => (lsrv1, lsrv2, ...))
-
- /** @var Array Map Server connections (server name => resource) */
- protected $conns = array();
-
- protected $connTimeout; // float number of seconds
- protected $session = ''; // random SHA-1 string
-
- /**
- * Construct a new instance from configuration.
- *
- * $config paramaters include:
- * 'lockServers' : Associative array of server names to configuration.
- * Configuration is an associative array that includes:
- * 'host' - IP address/hostname
- * 'port' - TCP port
- * 'authKey' - Secret string the lock server uses
- * 'srvsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
- * each having an odd-numbered list of server names (peers) as values.
- * 'connTimeout' : Lock server connection attempt timeout. [optional]
- *
- * @param Array $config
- */
- public function __construct( array $config ) {
- $this->lockServers = $config['lockServers'];
- // Sanitize srvsByBucket config to prevent PHP errors
- $this->srvsByBucket = array_filter( $config['srvsByBucket'], 'is_array' );
- $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
-
- if ( isset( $config['connTimeout'] ) ) {
- $this->connTimeout = $config['connTimeout'];
- } else {
- $this->connTimeout = 3; // use some sane amount
- }
-
- $this->session = '';
- for ( $i = 0; $i < 5; $i++ ) {
- $this->session .= mt_rand( 0, 2147483647 );
- }
- $this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
- }
-
- protected function doLock( array $paths, $type ) {
- $status = Status::newGood();
-
- $pathsToLock = array();
- // Get locks that need to be acquired (buckets => locks)...
- foreach ( $paths as $path ) {
- if ( isset( $this->locksHeld[$path][$type] ) ) {
- ++$this->locksHeld[$path][$type];
- } elseif ( isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
- $this->locksHeld[$path][$type] = 1;
- } else {
- $bucket = $this->getBucketFromKey( $path );
- $pathsToLock[$bucket][] = $path;
- }
- }
-
- $lockedPaths = array(); // files locked in this attempt
- // Attempt to acquire these locks...
- foreach ( $pathsToLock as $bucket => $paths ) {
- // Try to acquire the locks for this bucket
- $res = $this->doLockingRequestAll( $bucket, $paths, $type );
- if ( $res === 'cantacquire' ) {
- // Resources already locked by another process.
- // Abort and unlock everything we just locked.
- foreach ( $paths as $path ) {
- $status->fatal( 'lockmanager-fail-acquirelock', $path );
- }
- $status->merge( $this->doUnlock( $lockedPaths, $type ) );
- return $status;
- } elseif ( $res !== true ) {
- // Couldn't contact any servers for this bucket.
- // Abort and unlock everything we just locked.
- foreach ( $paths as $path ) {
- $status->fatal( 'lockmanager-fail-acquirelock', $path );
- }
- $status->merge( $this->doUnlock( $lockedPaths, $type ) );
- return $status;
- }
- // Record these locks as active
- foreach ( $paths as $path ) {
- $this->locksHeld[$path][$type] = 1; // locked
- }
- // Keep track of what locks were made in this attempt
- $lockedPaths = array_merge( $lockedPaths, $paths );
- }
-
- return $status;
- }
-
- protected function doUnlock( array $paths, $type ) {
- $status = Status::newGood();
-
- foreach ( $paths as $path ) {
- if ( !isset( $this->locksHeld[$path] ) ) {
- $status->warning( 'lockmanager-notlocked', $path );
- } elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
- $status->warning( 'lockmanager-notlocked', $path );
- } else {
- --$this->locksHeld[$path][$type];
- if ( $this->locksHeld[$path][$type] <= 0 ) {
- unset( $this->locksHeld[$path][$type] );
- }
- if ( !count( $this->locksHeld[$path] ) ) {
- unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
- }
- }
- }
-
- // Reference count the locks held and release locks when zero
- if ( !count( $this->locksHeld ) ) {
- $status->merge( $this->releaseLocks() );
- }
-
- return $status;
- }
-
- /**
- * Get a connection to a lock server and acquire locks on $paths
- *
- * @param $lockSrv string
- * @param $paths Array
- * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
- * @return bool Resources able to be locked
- */
- protected function doLockingRequest( $lockSrv, array $paths, $type ) {
- if ( $type == self::LOCK_SH ) { // reader locks
- $type = 'SH';
- } elseif ( $type == self::LOCK_EX ) { // writer locks
- $type = 'EX';
- } else {
- return true; // ok...
- }
-
- // Send out the command and get the response...
- $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
- $response = $this->sendCommand( $lockSrv, 'ACQUIRE', $type, $keys );
-
- return ( $response === 'ACQUIRED' );
- }
-
- /**
- * Send a command and get back the response
- *
- * @param $lockSrv string
- * @param $action string
- * @param $type string
- * @param $values Array
- * @return string|false
- */
- protected function sendCommand( $lockSrv, $action, $type, $values ) {
- $conn = $this->getConnection( $lockSrv );
- if ( !$conn ) {
- return false; // no connection
- }
- $authKey = $this->lockServers[$lockSrv]['authKey'];
- // Build of the command as a flat string...
- $values = implode( '|', $values );
- $key = sha1( $this->session . $action . $type . $values . $authKey );
- // Send out the command...
- if ( fwrite( $conn, "{$this->session}:$key:$action:$type:$values\n" ) === false ) {
- return false;
- }
- // Get the response...
- $response = fgets( $conn );
- if ( $response === false ) {
- return false;
- }
- return trim( $response );
- }
-
- /**
- * Attempt to acquire locks with the peers for a bucket
- *
- * @param $bucket integer
- * @param $paths Array List of resource keys to lock
- * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
- * @return bool|string One of (true, 'cantacquire', 'srverrors')
- */
- protected function doLockingRequestAll( $bucket, array $paths, $type ) {
- $yesVotes = 0; // locks made on trustable servers
- $votesLeft = count( $this->srvsByBucket[$bucket] ); // remaining peers
- $quorum = floor( $votesLeft/2 + 1 ); // simple majority
- // Get votes for each peer, in order, until we have enough...
- foreach ( $this->srvsByBucket[$bucket] as $lockSrv ) {
- // Attempt to acquire the lock on this peer
- if ( !$this->doLockingRequest( $lockSrv, $paths, $type ) ) {
- return 'cantacquire'; // vetoed; resource locked
- }
- ++$yesVotes; // success for this peer
- if ( $yesVotes >= $quorum ) {
- return true; // lock obtained
- }
- --$votesLeft;
- $votesNeeded = $quorum - $yesVotes;
- if ( $votesNeeded > $votesLeft ) {
- // In "trust cache" mode we don't have to meet the quorum
- break; // short-circuit
- }
- }
- // At this point, we must not have meet the quorum
- return 'srverrors'; // not enough votes to ensure correctness
- }
-
- /**
- * Get (or reuse) a connection to a lock server
- *
- * @param $lockSrv string
- * @return resource
- */
- protected function getConnection( $lockSrv ) {
- if ( !isset( $this->conns[$lockSrv] ) ) {
- $cfg = $this->lockServers[$lockSrv];
- wfSuppressWarnings();
- $errno = $errstr = '';
- $conn = fsockopen( $cfg['host'], $cfg['port'], $errno, $errstr, $this->connTimeout );
- wfRestoreWarnings();
- if ( $conn === false ) {
- return null;
- }
- $sec = floor( $this->connTimeout );
- $usec = floor( ( $this->connTimeout - floor( $this->connTimeout ) ) * 1e6 );
- stream_set_timeout( $conn, $sec, $usec );
- $this->conns[$lockSrv] = $conn;
- }
- return $this->conns[$lockSrv];
- }
-
- /**
- * Release all locks that this session is holding
- *
- * @return Status
- */
- protected function releaseLocks() {
- $status = Status::newGood();
- foreach ( $this->conns as $lockSrv => $conn ) {
- $response = $this->sendCommand( $lockSrv, 'RELEASE_ALL', '', array() );
- if ( $response !== 'RELEASED_ALL' ) {
- $status->fatal( 'lockmanager-fail-svr-release', $lockSrv );
- }
- }
- return $status;
- }
-
- /**
- * Get the bucket for resource path.
- * This should avoid throwing any exceptions.
- *
- * @param $path string
- * @return integer
- */
- protected function getBucketFromKey( $path ) {
- $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
- return intval( base_convert( $prefix, 16, 10 ) ) % count( $this->srvsByBucket );
- }
-
- /**
- * Make sure remaining locks get cleared for sanity
- */
- function __destruct() {
- $this->releaseLocks();
- foreach ( $this->conns as $conn ) {
- fclose( $conn );
- }
- }
-}
diff --git a/includes/filerepo/backend/lockmanager/LockManager.php b/includes/filerepo/backend/lockmanager/LockManager.php
deleted file mode 100644
index 23603a4f..00000000
--- a/includes/filerepo/backend/lockmanager/LockManager.php
+++ /dev/null
@@ -1,182 +0,0 @@
-<?php
-/**
- * @defgroup LockManager Lock management
- * @ingroup FileBackend
- */
-
-/**
- * @file
- * @ingroup LockManager
- * @author Aaron Schulz
- */
-
-/**
- * Class for handling resource locking.
- *
- * Locks on resource keys can either be shared or exclusive.
- *
- * Implementations must keep track of what is locked by this proccess
- * in-memory and support nested locking calls (using reference counting).
- * At least LOCK_UW and LOCK_EX must be implemented. LOCK_SH can be a no-op.
- * Locks should either be non-blocking or have low wait timeouts.
- *
- * Subclasses should avoid throwing exceptions at all costs.
- *
- * @ingroup LockManager
- * @since 1.19
- */
-abstract class LockManager {
- /** @var Array Mapping of lock types to the type actually used */
- protected $lockTypeMap = array(
- self::LOCK_SH => self::LOCK_SH,
- self::LOCK_UW => self::LOCK_EX, // subclasses may use self::LOCK_SH
- self::LOCK_EX => self::LOCK_EX
- );
-
- /** @var Array Map of (resource path => lock type => count) */
- protected $locksHeld = array();
-
- /* Lock types; stronger locks have higher values */
- const LOCK_SH = 1; // shared lock (for reads)
- const LOCK_UW = 2; // shared lock (for reads used to write elsewhere)
- const LOCK_EX = 3; // exclusive lock (for writes)
-
- /**
- * Construct a new instance from configuration
- *
- * @param $config Array
- */
- public function __construct( array $config ) {}
-
- /**
- * Lock the resources at the given abstract paths
- *
- * @param $paths Array List of resource names
- * @param $type integer LockManager::LOCK_* constant
- * @return Status
- */
- final public function lock( array $paths, $type = self::LOCK_EX ) {
- return $this->doLock( array_unique( $paths ), $this->lockTypeMap[$type] );
- }
-
- /**
- * Unlock the resources at the given abstract paths
- *
- * @param $paths Array List of storage paths
- * @param $type integer LockManager::LOCK_* constant
- * @return Status
- */
- final public function unlock( array $paths, $type = self::LOCK_EX ) {
- return $this->doUnlock( array_unique( $paths ), $this->lockTypeMap[$type] );
- }
-
- /**
- * Get the base 36 SHA-1 of a string, padded to 31 digits
- *
- * @param $path string
- * @return string
- */
- final protected static function sha1Base36( $path ) {
- return wfBaseConvert( sha1( $path ), 16, 36, 31 );
- }
-
- /**
- * Lock resources with the given keys and lock type
- *
- * @param $paths Array List of storage paths
- * @param $type integer LockManager::LOCK_* constant
- * @return string
- */
- abstract protected function doLock( array $paths, $type );
-
- /**
- * Unlock resources with the given keys and lock type
- *
- * @param $paths Array List of storage paths
- * @param $type integer LockManager::LOCK_* constant
- * @return string
- */
- abstract protected function doUnlock( array $paths, $type );
-}
-
-/**
- * Self releasing locks
- *
- * LockManager helper class to handle scoped locks, which
- * release when an object is destroyed or goes out of scope.
- *
- * @ingroup LockManager
- * @since 1.19
- */
-class ScopedLock {
- /** @var LockManager */
- protected $manager;
- /** @var Status */
- protected $status;
- /** @var Array List of resource paths*/
- protected $paths;
-
- protected $type; // integer lock type
-
- /**
- * @param $manager LockManager
- * @param $paths Array List of storage paths
- * @param $type integer LockManager::LOCK_* constant
- * @param $status Status
- */
- protected function __construct(
- LockManager $manager, array $paths, $type, Status $status
- ) {
- $this->manager = $manager;
- $this->paths = $paths;
- $this->status = $status;
- $this->type = $type;
- }
-
- protected function __clone() {}
-
- /**
- * Get a ScopedLock object representing a lock on resource paths.
- * Any locks are released once this object goes out of scope.
- * The status object is updated with any errors or warnings.
- *
- * @param $manager LockManager
- * @param $paths Array List of storage paths
- * @param $type integer LockManager::LOCK_* constant
- * @param $status Status
- * @return ScopedLock|null Returns null on failure
- */
- public static function factory(
- LockManager $manager, array $paths, $type, Status $status
- ) {
- $lockStatus = $manager->lock( $paths, $type );
- $status->merge( $lockStatus );
- if ( $lockStatus->isOK() ) {
- return new self( $manager, $paths, $type, $status );
- }
- return null;
- }
-
- function __destruct() {
- $wasOk = $this->status->isOK();
- $this->status->merge( $this->manager->unlock( $this->paths, $this->type ) );
- if ( $wasOk ) {
- // Make sure status is OK, despite any unlockFiles() fatals
- $this->status->setResult( true, $this->status->value );
- }
- }
-}
-
-/**
- * Simple version of LockManager that does nothing
- * @since 1.19
- */
-class NullLockManager extends LockManager {
- protected function doLock( array $paths, $type ) {
- return Status::newGood();
- }
-
- protected function doUnlock( array $paths, $type ) {
- return Status::newGood();
- }
-}
diff --git a/includes/filerepo/backend/lockmanager/LockManagerGroup.php b/includes/filerepo/backend/lockmanager/LockManagerGroup.php
deleted file mode 100644
index 11e77972..00000000
--- a/includes/filerepo/backend/lockmanager/LockManagerGroup.php
+++ /dev/null
@@ -1,89 +0,0 @@
-<?php
-/**
- * Class to handle file lock manager registration
- *
- * @ingroup LockManager
- * @author Aaron Schulz
- * @since 1.19
- */
-class LockManagerGroup {
-
- /**
- * @var LockManagerGroup
- */
- protected static $instance = null;
-
- /** @var Array of (name => ('class' =>, 'config' =>, 'instance' =>)) */
- protected $managers = array();
-
- protected function __construct() {}
- protected function __clone() {}
-
- /**
- * @return LockManagerGroup
- */
- public static function singleton() {
- if ( self::$instance == null ) {
- self::$instance = new self();
- self::$instance->initFromGlobals();
- }
- return self::$instance;
- }
-
- /**
- * Register lock managers from the global variables
- *
- * @return void
- */
- protected function initFromGlobals() {
- global $wgLockManagers;
-
- $this->register( $wgLockManagers );
- }
-
- /**
- * Register an array of file lock manager configurations
- *
- * @param $configs Array
- * @return void
- * @throws MWException
- */
- protected function register( array $configs ) {
- foreach ( $configs as $config ) {
- if ( !isset( $config['name'] ) ) {
- throw new MWException( "Cannot register a lock manager with no name." );
- }
- $name = $config['name'];
- if ( !isset( $config['class'] ) ) {
- throw new MWException( "Cannot register lock manager `{$name}` with no class." );
- }
- $class = $config['class'];
- unset( $config['class'] ); // lock manager won't need this
- $this->managers[$name] = array(
- 'class' => $class,
- 'config' => $config,
- 'instance' => null
- );
- }
- }
-
- /**
- * Get the lock manager object with a given name
- *
- * @param $name string
- * @return LockManager
- * @throws MWException
- */
- public function get( $name ) {
- if ( !isset( $this->managers[$name] ) ) {
- throw new MWException( "No lock manager defined with the name `$name`." );
- }
- // Lazy-load the actual lock manager instance
- if ( !isset( $this->managers[$name]['instance'] ) ) {
- $class = $this->managers[$name]['class'];
- $config = $this->managers[$name]['config'];
- $this->managers[$name]['instance'] = new $class( $config );
- }
- return $this->managers[$name]['instance'];
- }
-}
diff --git a/includes/filerepo/file/ArchivedFile.php b/includes/filerepo/file/ArchivedFile.php
index 3b9bd7f0..c5a0bd1b 100644
--- a/includes/filerepo/file/ArchivedFile.php
+++ b/includes/filerepo/file/ArchivedFile.php
@@ -1,6 +1,21 @@
<?php
/**
- * Deleted file in the 'filearchive' table
+ * Deleted file in the 'filearchive' table.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileAbstraction
@@ -93,7 +108,7 @@ class ArchivedFile {
/**
* Loads a file object from the filearchive table
- * @return true on success or null
+ * @return bool|null True on success or null
*/
public function load() {
if ( $this->dataLoaded ) {
@@ -143,7 +158,7 @@ class ArchivedFile {
array( 'ORDER BY' => 'fa_timestamp DESC' ) );
if ( $res == false || $dbr->numRows( $res ) == 0 ) {
// this revision does not exist?
- return;
+ return null;
}
$ret = $dbr->resultObject( $res );
$row = $ret->fetchObject();
diff --git a/includes/filerepo/file/File.php b/includes/filerepo/file/File.php
index f74fb678..557609d4 100644
--- a/includes/filerepo/file/File.php
+++ b/includes/filerepo/file/File.php
@@ -9,6 +9,21 @@
/**
* Base code for files.
*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
* @file
* @ingroup FileAbstraction
*/
@@ -48,6 +63,14 @@ abstract class File {
const DELETE_SOURCE = 1;
+ // Audience options for File::getDescription()
+ const FOR_PUBLIC = 1;
+ const FOR_THIS_USER = 2;
+ const RAW = 3;
+
+ // Options for File::thumbName()
+ const THUMB_FULL_NAME = 1;
+
/**
* Some member variables can be lazy-initialised using __get(). The
* initialisation function for these variables is always a function named
@@ -68,19 +91,19 @@ abstract class File {
*/
/**
- * @var FileRepo|false
+ * @var FileRepo|bool
*/
var $repo;
/**
- * @var Title|false
+ * @var Title
*/
var $title;
var $lastError, $redirected, $redirectedTitle;
/**
- * @var FSFile|false
+ * @var FSFile|bool False if undefined
*/
protected $fsFile;
@@ -94,6 +117,8 @@ abstract class File {
*/
protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
+ protected $redirectTitle;
+
/**
* @var bool
*/
@@ -111,8 +136,8 @@ abstract class File {
* may return false or throw exceptions if they are not set.
* Most subclasses will want to call assertRepoDefined() here.
*
- * @param $title Title|string|false
- * @param $repo FileRepo|false
+ * @param $title Title|string|bool
+ * @param $repo FileRepo|bool
*/
function __construct( $title, $repo ) {
if ( $title !== false ) { // subclasses may not use MW titles
@@ -127,7 +152,8 @@ abstract class File {
* valid Title object with namespace NS_FILE or null
*
* @param $title Title|string
- * @param $exception string|false Use 'exception' to throw an error on bad titles
+ * @param $exception string|bool Use 'exception' to throw an error on bad titles
+ * @throws MWException
* @return Title|null
*/
static function normalizeTitle( $title, $exception = false ) {
@@ -223,6 +249,18 @@ abstract class File {
}
/**
+ * Callback for usort() to do file sorts by name
+ *
+ * @param $a File
+ * @param $b File
+ *
+ * @return Integer: result of name comparison
+ */
+ public static function compare( File $a, File $b ) {
+ return strcmp( $a->getName(), $b->getName() );
+ }
+
+ /**
* Return the name of this file
*
* @return string
@@ -252,7 +290,7 @@ abstract class File {
/**
* Return the associated title object
*
- * @return Title|false
+ * @return Title
*/
public function getTitle() {
return $this->title;
@@ -319,17 +357,17 @@ abstract class File {
}
/**
- * Return the storage path to the file. Note that this does
- * not mean that a file actually exists under that location.
- *
- * This path depends on whether directory hashing is active or not,
- * i.e. whether the files are all found in the same directory,
- * or in hashed paths like /images/3/3c.
- *
- * Most callers don't check the return value, but ForeignAPIFile::getPath
- * returns false.
+ * Return the storage path to the file. Note that this does
+ * not mean that a file actually exists under that location.
+ *
+ * This path depends on whether directory hashing is active or not,
+ * i.e. whether the files are all found in the same directory,
+ * or in hashed paths like /images/3/3c.
+ *
+ * Most callers don't check the return value, but ForeignAPIFile::getPath
+ * returns false.
*
- * @return string|false
+ * @return string|bool ForeignAPIFile::getPath can return false
*/
public function getPath() {
if ( !isset( $this->path ) ) {
@@ -344,7 +382,7 @@ abstract class File {
* Returns false on failure. Callers must not alter the file.
* Temporary files are cleared automatically.
*
- * @return string|false
+ * @return string|bool False on failure
*/
public function getLocalRefPath() {
$this->assertRepoDefined();
@@ -383,7 +421,7 @@ abstract class File {
*
* @param $page int
*
- * @return false|number
+ * @return bool|number False on failure
*/
public function getHeight( $page = 1 ) {
return false;
@@ -430,9 +468,43 @@ abstract class File {
}
/**
+ * Will the thumbnail be animated if one would expect it to be.
+ *
+ * Currently used to add a warning to the image description page
+ *
+ * @return bool false if the main image is both animated
+ * and the thumbnail is not. In all other cases must return
+ * true. If image is not renderable whatsoever, should
+ * return true.
+ */
+ public function canAnimateThumbIfAppropriate() {
+ $handler = $this->getHandler();
+ if ( !$handler ) {
+ // We cannot handle image whatsoever, thus
+ // one would not expect it to be animated
+ // so true.
+ return true;
+ } else {
+ if ( $this->allowInlineDisplay()
+ && $handler->isAnimatedImage( $this )
+ && !$handler->canAnimateThumbnail( $this )
+ ) {
+ // Image is animated, but thumbnail isn't.
+ // This is unexpected to the user.
+ return false;
+ } else {
+ // Image is not animated, so one would
+ // not expect thumb to be
+ return true;
+ }
+ }
+ }
+
+ /**
* Get handler-specific metadata
* Overridden by LocalFile, UnregisteredLocalFile
* STUB
+ * @return bool
*/
public function getMetadata() {
return false;
@@ -462,6 +534,7 @@ abstract class File {
* Return the bit depth of the file
* Overridden by LocalFile
* STUB
+ * @return int
*/
public function getBitDepth() {
return 0;
@@ -471,6 +544,7 @@ abstract class File {
* Return the size of the image file, in bytes
* Overridden by LocalFile, UnregisteredLocalFile
* STUB
+ * @return bool
*/
public function getSize() {
return false;
@@ -492,6 +566,7 @@ abstract class File {
* Use the value returned by this function with the MEDIATYPE_xxx constants.
* Overridden by LocalFile,
* STUB
+ * @return string
*/
function getMediaType() {
return MEDIATYPE_UNKNOWN;
@@ -518,6 +593,7 @@ abstract class File {
/**
* Accessor for __get()
+ * @return bool
*/
protected function getCanRender() {
return $this->canRender();
@@ -686,15 +762,19 @@ abstract class File {
}
/**
- * Return the file name of a thumbnail with the specified parameters
+ * Return the file name of a thumbnail with the specified parameters.
+ * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
+ * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
*
* @param $params Array: handler-specific parameters
- * @private -ish
- *
+ * @param $flags integer Bitfield that supports THUMB_* constants
* @return string
*/
- function thumbName( $params ) {
- return $this->generateThumbName( $this->getName(), $params );
+ public function thumbName( $params, $flags = 0 ) {
+ $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
+ ? $this->repo->nameForThumb( $this->getName() )
+ : $this->getName();
+ return $this->generateThumbName( $name, $params );
}
/**
@@ -705,7 +785,7 @@ abstract class File {
*
* @return string
*/
- function generateThumbName( $name, $params ) {
+ public function generateThumbName( $name, $params ) {
if ( !$this->getHandler() ) {
return null;
}
@@ -750,7 +830,7 @@ abstract class File {
/**
* Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
- *
+ *
* @param $thumbPath string Thumbnail storage path
* @param $thumbUrl string Thumbnail URL
* @param $params Array
@@ -764,7 +844,7 @@ abstract class File {
return $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
} else {
return new MediaTransformError( 'thumbnail_error',
- $params['width'], 0, wfMsg( 'thumbnail-dest-create' ) );
+ $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
}
}
@@ -774,7 +854,7 @@ abstract class File {
* @param $params Array: an associative array of handler-specific parameters.
* Typical keys are width, height and page.
* @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
- * @return MediaTransformOutput|false
+ * @return MediaTransformOutput|bool False on failure
*/
function transform( $params, $flags = 0 ) {
global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
@@ -837,6 +917,13 @@ abstract class File {
}
}
+ // If the backend is ready-only, don't keep generating thumbnails
+ // only to return transformation errors, just return the error now.
+ if ( $this->repo->getReadOnlyReason() !== false ) {
+ $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
+ break;
+ }
+
// Create a temp FS file with the same extension and the thumbnail
$thumbExt = FileBackend::extensionFromPath( $thumbPath );
$tmpFile = TempFSFile::factory( 'transform_', $thumbExt );
@@ -847,7 +934,9 @@ abstract class File {
$tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
// Actually render the thumbnail...
+ wfProfileIn( __METHOD__ . '-doTransform' );
$thumb = $this->handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
+ wfProfileOut( __METHOD__ . '-doTransform' );
$tmpFile->bind( $thumb ); // keep alive with $thumb
if ( !$thumb ) { // bad params?
@@ -859,19 +948,16 @@ abstract class File {
$thumb = $this->handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
}
} elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
- $backend = $this->repo->getBackend();
- // Copy the thumbnail from the file system into storage. This avoids using
- // FileRepo::store(); getThumbPath() uses a different zone in some subclasses.
- $backend->prepare( array( 'dir' => dirname( $thumbPath ) ) );
- $status = $backend->store(
- array( 'src' => $tmpThumbPath, 'dst' => $thumbPath, 'overwrite' => 1 ),
- array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1 )
- );
+ // Copy the thumbnail from the file system into storage...
+ $disposition = $this->getThumbDisposition( $thumbName );
+ $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
if ( $status->isOK() ) {
$thumb->setStoragePath( $thumbPath );
} else {
$thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
}
+ // Give extensions a chance to do something with this thumbnail...
+ wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
}
// Purge. Useful in the event of Core -> Squid connection failure or squid
@@ -889,6 +975,19 @@ abstract class File {
}
/**
+ * @param $thumbName string Thumbnail name
+ * @return string Content-Disposition header value
+ */
+ function getThumbDisposition( $thumbName ) {
+ $fileName = $this->name; // file name to suggest
+ $thumbExt = FileBackend::extensionFromPath( $thumbName );
+ if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
+ $fileName .= ".$thumbExt";
+ }
+ return FileBackend::makeContentDisposition( 'inline', $fileName );
+ }
+
+ /**
* Hook into transform() to allow migration of thumbnail files
* STUB
* Overridden by LocalFile
@@ -920,7 +1019,8 @@ abstract class File {
$path = '/common/images/icons/' . $icon;
$filepath = $wgStyleDirectory . $path;
if ( file_exists( $filepath ) ) { // always FS
- return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
+ $params = array( 'width' => 120, 'height' => 120 );
+ return new ThumbnailImage( $this, $wgStylePath . $path, false, $params );
}
}
return null;
@@ -938,6 +1038,7 @@ abstract class File {
* Get all thumbnail names previously generated for this file
* STUB
* Overridden by LocalFile
+ * @return array
*/
function getThumbnails() {
return array();
@@ -987,13 +1088,13 @@ abstract class File {
*
* STUB
* @param $limit integer Limit of rows to return
- * @param $start timestamp Only revisions older than $start will be returned
- * @param $end timestamp Only revisions newer than $end will be returned
+ * @param $start string timestamp Only revisions older than $start will be returned
+ * @param $end string timestamp Only revisions newer than $end will be returned
* @param $inc bool Include the endpoints of the time range
*
* @return array
*/
- function getHistory($limit = null, $start = null, $end = null, $inc=true) {
+ function getHistory( $limit = null, $start = null, $end = null, $inc=true ) {
return array();
}
@@ -1004,6 +1105,7 @@ abstract class File {
*
* STUB
* Overridden in LocalFile
+ * @return bool
*/
public function nextHistoryLine() {
return false;
@@ -1185,7 +1287,7 @@ abstract class File {
*
* @param $suffix bool|string if not false, the name of a thumbnail file
*
- * @return path
+ * @return string path
*/
function getThumbUrl( $suffix = false ) {
$this->assertRepoDefined();
@@ -1251,7 +1353,7 @@ abstract class File {
*/
function isHashed() {
$this->assertRepoDefined();
- return $this->repo->isHashed();
+ return (bool)$this->repo->getHashLevels();
}
/**
@@ -1329,7 +1431,7 @@ abstract class File {
/**
* Returns the repository
*
- * @return FileRepo|false
+ * @return FileRepo|bool
*/
function getRepo() {
return $this->repo;
@@ -1360,6 +1462,7 @@ abstract class File {
/**
* Return the deletion bitfield
* STUB
+ * @return int
*/
function getVisibility() {
return 0;
@@ -1401,7 +1504,7 @@ abstract class File {
*
* @param $reason String
* @param $suppress Boolean: hide content from sysops?
- * @return true on success, false on some kind of failure
+ * @return bool on success, false on some kind of failure
* STUB
* Overridden by LocalFile
*/
@@ -1418,7 +1521,7 @@ abstract class File {
* @param $versions array set of record ids of deleted items to restore,
* or empty to restore all revisions.
* @param $unsuppress bool remove restrictions on content upon restoration?
- * @return int|false the number of file revisions restored if successful,
+ * @return int|bool the number of file revisions restored if successful,
* or false on failure
* STUB
* Overridden by LocalFile
@@ -1442,7 +1545,7 @@ abstract class File {
* Returns the number of pages of a multipage document, or false for
* documents which aren't multipage documents
*
- * @return false|int
+ * @return bool|int
*/
function pageCount() {
if ( !isset( $this->pageCount ) ) {
@@ -1536,19 +1639,25 @@ abstract class File {
}
/**
- * Get discription of file revision
+ * Get description of file revision
* STUB
*
+ * @param $audience Integer: one of:
+ * File::FOR_PUBLIC to be displayed to all users
+ * File::FOR_THIS_USER to be displayed to the given user
+ * File::RAW get the description regardless of permissions
+ * @param $user User object to check for, only if FOR_THIS_USER is passed
+ * to the $audience parameter
* @return string
*/
- function getDescription() {
+ function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
return null;
}
/**
* Get the 14-character timestamp of the file upload
*
- * @return string|false TS_MW timestamp or false on failure
+ * @return string|bool TS_MW timestamp or false on failure
*/
function getTimestamp() {
$this->assertRepoDefined();
@@ -1566,7 +1675,7 @@ abstract class File {
}
/**
- * Get the deletion archive key, <sha1>.<ext>
+ * Get the deletion archive key, "<sha1>.<ext>"
*
* @return string
*/
@@ -1618,7 +1727,7 @@ abstract class File {
*
* @param $path string
*
- * @return false|string False on failure
+ * @return bool|string False on failure
*/
static function sha1Base36( $path ) {
wfDeprecated( __METHOD__, '1.19' );
@@ -1698,6 +1807,14 @@ abstract class File {
}
/**
+ * Check if this file object is small and can be cached
+ * @return boolean
+ */
+ public function isCacheable() {
+ return true;
+ }
+
+ /**
* Assert that $this->repo is set to a valid FileRepo instance
* @throws MWException
*/
diff --git a/includes/filerepo/file/ForeignAPIFile.php b/includes/filerepo/file/ForeignAPIFile.php
index 681544fd..56482611 100644
--- a/includes/filerepo/file/ForeignAPIFile.php
+++ b/includes/filerepo/file/ForeignAPIFile.php
@@ -2,6 +2,21 @@
/**
* Foreign file accessible through api.php requests.
*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
* @file
* @ingroup FileAbstraction
*/
@@ -39,9 +54,9 @@ class ForeignAPIFile extends File {
*/
static function newFromTitle( Title $title, $repo ) {
$data = $repo->fetchImageQuery( array(
- 'titles' => 'File:' . $title->getDBKey(),
- 'iiprop' => self::getProps(),
- 'prop' => 'imageinfo',
+ 'titles' => 'File:' . $title->getDBKey(),
+ 'iiprop' => self::getProps(),
+ 'prop' => 'imageinfo',
'iimetadataversion' => MediaHandler::getMetadataVersion()
) );
@@ -68,20 +83,33 @@ class ForeignAPIFile extends File {
/**
* Get the property string for iiprop and aiprop
+ * @return string
*/
static function getProps() {
return 'timestamp|user|comment|url|size|sha1|metadata|mime';
}
// Dummy functions...
+
+ /**
+ * @return bool
+ */
public function exists() {
return $this->mExists;
}
+ /**
+ * @return bool
+ */
public function getPath() {
return false;
}
+ /**
+ * @param Array $params
+ * @param int $flags
+ * @return bool|MediaTransformOutput
+ */
function transform( $params, $flags = 0 ) {
if( !$this->canRender() ) {
// show icon
@@ -101,6 +129,11 @@ class ForeignAPIFile extends File {
}
// Info we can get from API...
+
+ /**
+ * @param $page int
+ * @return int|number
+ */
public function getWidth( $page = 1 ) {
return isset( $this->mInfo['width'] ) ? intval( $this->mInfo['width'] ) : 0;
}
@@ -113,6 +146,9 @@ class ForeignAPIFile extends File {
return isset( $this->mInfo['height'] ) ? intval( $this->mInfo['height'] ) : 0;
}
+ /**
+ * @return bool|null|string
+ */
public function getMetadata() {
if ( isset( $this->mInfo['metadata'] ) ) {
return serialize( self::parseMetadata( $this->mInfo['metadata'] ) );
@@ -120,6 +156,10 @@ class ForeignAPIFile extends File {
return null;
}
+ /**
+ * @param $metadata array
+ * @return array
+ */
public static function parseMetadata( $metadata ) {
if( !is_array( $metadata ) ) {
return $metadata;
@@ -131,28 +171,47 @@ class ForeignAPIFile extends File {
return $ret;
}
+ /**
+ * @return bool|int|null
+ */
public function getSize() {
return isset( $this->mInfo['size'] ) ? intval( $this->mInfo['size'] ) : null;
}
+ /**
+ * @return null|string
+ */
public function getUrl() {
return isset( $this->mInfo['url'] ) ? strval( $this->mInfo['url'] ) : null;
}
+ /**
+ * @param string $method
+ * @return int|null|string
+ */
public function getUser( $method='text' ) {
return isset( $this->mInfo['user'] ) ? strval( $this->mInfo['user'] ) : null;
}
- public function getDescription() {
+ /**
+ * @return null|string
+ */
+ public function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
return isset( $this->mInfo['comment'] ) ? strval( $this->mInfo['comment'] ) : null;
}
+ /**
+ * @return null|String
+ */
function getSha1() {
return isset( $this->mInfo['sha1'] )
? wfBaseConvert( strval( $this->mInfo['sha1'] ), 16, 36, 31 )
: null;
}
+ /**
+ * @return bool|Mixed|string
+ */
function getTimestamp() {
return wfTimestamp( TS_MW,
isset( $this->mInfo['timestamp'] )
@@ -161,6 +220,9 @@ class ForeignAPIFile extends File {
);
}
+ /**
+ * @return string
+ */
function getMimeType() {
if( !isset( $this->mInfo['mime'] ) ) {
$magic = MimeMagic::singleton();
@@ -169,12 +231,18 @@ class ForeignAPIFile extends File {
return $this->mInfo['mime'];
}
- /// @todo FIXME: May guess wrong on file types that can be eg audio or video
+ /**
+ * @todo FIXME: May guess wrong on file types that can be eg audio or video
+ * @return int|string
+ */
function getMediaType() {
$magic = MimeMagic::singleton();
return $magic->getMediaType( null, $this->getMimeType() );
}
+ /**
+ * @return bool|string
+ */
function getDescriptionUrl() {
return isset( $this->mInfo['descriptionurl'] )
? $this->mInfo['descriptionurl']
@@ -183,6 +251,8 @@ class ForeignAPIFile extends File {
/**
* Only useful if we're locally caching thumbs anyway...
+ * @param $suffix string
+ * @return null|string
*/
function getThumbPath( $suffix = '' ) {
if ( $this->repo->canCacheThumbs() ) {
@@ -196,6 +266,9 @@ class ForeignAPIFile extends File {
}
}
+ /**
+ * @return array
+ */
function getThumbnails() {
$dir = $this->getThumbPath( $this->getName() );
$iter = $this->repo->getBackend()->getFileList( array( 'dir' => $dir ) );
@@ -225,6 +298,9 @@ class ForeignAPIFile extends File {
$wgMemc->delete( $key );
}
+ /**
+ * @param $options array
+ */
function purgeThumbnails( $options = array() ) {
global $wgMemc;
@@ -245,8 +321,8 @@ class ForeignAPIFile extends File {
}
# Delete the thumbnails
- $this->repo->cleanupBatch( $purgeList, FileRepo::SKIP_LOCKING );
+ $this->repo->quickPurgeBatch( $purgeList );
# Clear out the thumbnail directory if empty
- $this->repo->getBackend()->clean( array( 'dir' => $dir ) );
+ $this->repo->quickCleanDir( $dir );
}
}
diff --git a/includes/filerepo/file/ForeignDBFile.php b/includes/filerepo/file/ForeignDBFile.php
index 191a712d..91f6cb62 100644
--- a/includes/filerepo/file/ForeignDBFile.php
+++ b/includes/filerepo/file/ForeignDBFile.php
@@ -1,6 +1,21 @@
<?php
/**
- * Foreign file with an accessible MediaWiki database
+ * Foreign file with an accessible MediaWiki database.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileAbstraction
@@ -39,23 +54,52 @@ class ForeignDBFile extends LocalFile {
return $file;
}
+ /**
+ * @param $srcPath String
+ * @param $flags int
+ * @throws MWException
+ */
function publish( $srcPath, $flags = 0 ) {
$this->readOnlyError();
}
+ /**
+ * @param $oldver
+ * @param $desc string
+ * @param $license string
+ * @param $copyStatus string
+ * @param $source string
+ * @param $watch bool
+ * @param $timestamp bool|string
+ * @throws MWException
+ */
function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
$watch = false, $timestamp = false ) {
$this->readOnlyError();
}
+ /**
+ * @param $versions array
+ * @param $unsuppress bool
+ * @throws MWException
+ */
function restore( $versions = array(), $unsuppress = false ) {
$this->readOnlyError();
}
+ /**
+ * @param $reason string
+ * @param $suppress bool
+ * @throws MWException
+ */
function delete( $reason, $suppress = false ) {
$this->readOnlyError();
}
+ /**
+ * @param $target Title
+ * @throws MWException
+ */
function move( $target ) {
$this->readOnlyError();
}
diff --git a/includes/filerepo/file/LocalFile.php b/includes/filerepo/file/LocalFile.php
index 0f8b4754..695c4e9e 100644
--- a/includes/filerepo/file/LocalFile.php
+++ b/includes/filerepo/file/LocalFile.php
@@ -1,6 +1,21 @@
<?php
/**
- * Local file in the wiki's own database
+ * Local file in the wiki's own database.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileAbstraction
@@ -29,6 +44,8 @@ define( 'MW_FILE_VERSION', 8 );
* @ingroup FileAbstraction
*/
class LocalFile extends File {
+ const CACHE_FIELD_MAX_LEN = 1000;
+
/**#@+
* @private
*/
@@ -58,6 +75,11 @@ class LocalFile extends File {
/**#@-*/
+ /**
+ * @var LocalRepo
+ */
+ var $repo;
+
protected $repoClass = 'LocalRepo';
/**
@@ -121,6 +143,7 @@ class LocalFile extends File {
/**
* Fields in the image table
+ * @return array
*/
static function selectFields() {
return array(
@@ -160,6 +183,7 @@ class LocalFile extends File {
/**
* Get the memcached key for the main data for this file, or false if
* there is no access to the shared cache.
+ * @return bool
*/
function getCacheKey() {
$hashedName = md5( $this->getName() );
@@ -169,6 +193,7 @@ class LocalFile extends File {
/**
* Try to load file metadata from memcached. Returns true on success.
+ * @return bool
*/
function loadFromCache() {
global $wgMemc;
@@ -238,6 +263,10 @@ class LocalFile extends File {
$this->setProps( $props );
}
+ /**
+ * @param $prefix string
+ * @return array
+ */
function getCacheFields( $prefix = 'img_' ) {
static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
@@ -286,6 +315,10 @@ class LocalFile extends File {
/**
* Decode a row from the database (either object or array) to an array
* with timestamps and MIME types decoded, and the field prefix removed.
+ * @param $row
+ * @param $prefix string
+ * @throws MWException
+ * @return array
*/
function decodeRow( $row, $prefix = 'img_' ) {
$array = (array)$row;
@@ -407,6 +440,7 @@ class LocalFile extends File {
$dbw->update( 'image',
array(
+ 'img_size' => $this->size, // sanity
'img_width' => $this->width,
'img_height' => $this->height,
'img_bits' => $this->bits,
@@ -462,9 +496,12 @@ class LocalFile extends File {
/** getPath inherited */
/** isVisible inhereted */
+ /**
+ * @return bool
+ */
function isMissing() {
if ( $this->missing === null ) {
- list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl(), FileRepo::FILES_ONLY );
+ list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
$this->missing = !$fileExists;
}
return $this->missing;
@@ -473,7 +510,8 @@ class LocalFile extends File {
/**
* Return the width of the image
*
- * Returns false on error
+ * @param $page int
+ * @return bool|int Returns false on error
*/
public function getWidth( $page = 1 ) {
$this->load();
@@ -493,7 +531,8 @@ class LocalFile extends File {
/**
* Return the height of the image
*
- * Returns false on error
+ * @param $page int
+ * @return bool|int Returns false on error
*/
public function getHeight( $page = 1 ) {
$this->load();
@@ -514,6 +553,7 @@ class LocalFile extends File {
* Returns ID or name of user who uploaded the file
*
* @param $type string 'text' or 'id'
+ * @return int|string
*/
function getUser( $type = 'text' ) {
$this->load();
@@ -527,12 +567,16 @@ class LocalFile extends File {
/**
* Get handler-specific metadata
+ * @return string
*/
function getMetadata() {
$this->load();
return $this->metadata;
}
+ /**
+ * @return int
+ */
function getBitDepth() {
$this->load();
return $this->bits;
@@ -540,6 +584,7 @@ class LocalFile extends File {
/**
* Return the size of the image file, in bytes
+ * @return int
*/
public function getSize() {
$this->load();
@@ -548,6 +593,7 @@ class LocalFile extends File {
/**
* Returns the mime type of the file.
+ * @return string
*/
function getMimeType() {
$this->load();
@@ -557,6 +603,7 @@ class LocalFile extends File {
/**
* Return the type of the media in the file.
* Use the value returned by this function with the MEDIATYPE_xxx constants.
+ * @return string
*/
function getMediaType() {
$this->load();
@@ -586,6 +633,9 @@ class LocalFile extends File {
/**
* Fix thumbnail files from 1.4 or before, with extreme prejudice
+ * @todo : do we still care about this? Perhaps a maintenance script
+ * can be made instead. Enabling this code results in a serious
+ * RTT regression for wikis without 404 handling.
*/
function migrateThumbFile( $thumbName ) {
$thumbDir = $this->getThumbPath();
@@ -608,10 +658,12 @@ class LocalFile extends File {
}
*/
- if ( $this->repo->fileExists( $thumbDir, FileRepo::FILES_ONLY ) ) {
+ /*
+ if ( $this->repo->fileExists( $thumbDir ) ) {
// Delete file where directory should be
$this->repo->cleanupBatch( array( $thumbDir ) );
}
+ */
}
/** getHandler inherited */
@@ -620,12 +672,10 @@ class LocalFile extends File {
/**
* Get all thumbnail names previously generated for this file
- * @param $archiveName string|false Name of an archive file
+ * @param $archiveName string|bool Name of an archive file, default false
* @return array first element is the base dir, then files in that base dir.
*/
function getThumbnails( $archiveName = false ) {
- $this->load();
-
if ( $archiveName ) {
$dir = $this->getArchiveThumbPath( $archiveName );
} else {
@@ -690,6 +740,8 @@ class LocalFile extends File {
*/
function purgeOldThumbnails( $archiveName ) {
global $wgUseSquid;
+ wfProfileIn( __METHOD__ );
+
// Get a list of old thumbnails and URLs
$files = $this->getThumbnails( $archiveName );
$dir = array_shift( $files );
@@ -706,6 +758,8 @@ class LocalFile extends File {
}
SquidUpdate::purge( $urls );
}
+
+ wfProfileOut( __METHOD__ );
}
/**
@@ -713,6 +767,7 @@ class LocalFile extends File {
*/
function purgeThumbnails( $options = array() ) {
global $wgUseSquid;
+ wfProfileIn( __METHOD__ );
// Delete thumbnails
$files = $this->getThumbnails();
@@ -739,6 +794,8 @@ class LocalFile extends File {
}
SquidUpdate::purge( $urls );
}
+
+ wfProfileOut( __METHOD__ );
}
/**
@@ -763,14 +820,21 @@ class LocalFile extends File {
}
# Delete the thumbnails
- $this->repo->cleanupBatch( $purgeList, FileRepo::SKIP_LOCKING );
+ $this->repo->quickPurgeBatch( $purgeList );
# Clear out the thumbnail directory if empty
- $this->repo->getBackend()->clean( array( 'dir' => $dir ) );
+ $this->repo->quickCleanDir( $dir );
}
/** purgeDescription inherited */
/** purgeEverything inherited */
+ /**
+ * @param $limit null
+ * @param $start null
+ * @param $end null
+ * @param $inc bool
+ * @return array
+ */
function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
$dbr = $this->repo->getSlaveDB();
$tables = array( 'oldimage' );
@@ -824,6 +888,7 @@ class LocalFile extends File {
* 0 return line for current version
* 1 query for old versions, return first one
* 2, ... return next old version from above query
+ * @return bool
*/
public function nextHistoryLine() {
# Polymorphic function name to distinguish foreign and local fetches
@@ -888,21 +953,25 @@ class LocalFile extends File {
* @param $comment String: upload description
* @param $pageText String: text to use for the new description page,
* if a new description page is created
- * @param $flags Integer: flags for publish()
- * @param $props Array: File properties, if known. This can be used to reduce the
+ * @param $flags Integer|bool: flags for publish()
+ * @param $props Array|bool: File properties, if known. This can be used to reduce the
* upload time when uploading virtual URLs for which the file info
* is already known
- * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
- * @param $user Mixed: User object or null to use $wgUser
+ * @param $timestamp String|bool: timestamp for img_timestamp, or false to use the current time
+ * @param $user User|null: User object or null to use $wgUser
*
* @return FileRepoStatus object. On success, the value member contains the
* archive name, or an empty string if it was a new file.
*/
function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
global $wgContLang;
+
+ if ( $this->getRepo()->getReadOnlyReason() !== false ) {
+ return $this->readOnlyFatalStatus();
+ }
+
// truncate nicely or the DB will do it for us
- // non-nicely (dangling multi-byte chars, non-truncated
- // version in cache).
+ // non-nicely (dangling multi-byte chars, non-truncated version in cache).
$comment = $wgContLang->truncate( $comment, 255 );
$this->lock(); // begin
$status = $this->publish( $srcPath, $flags );
@@ -923,6 +992,14 @@ class LocalFile extends File {
/**
* Record a file upload in the upload log and the image table
+ * @param $oldver
+ * @param $desc string
+ * @param $license string
+ * @param $copyStatus string
+ * @param $source string
+ * @param $watch bool
+ * @param $timestamp string|bool
+ * @return bool
*/
function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
$watch = false, $timestamp = false )
@@ -942,20 +1019,31 @@ class LocalFile extends File {
/**
* Record a file upload in the upload log and the image table
+ * @param $oldver
+ * @param $comment string
+ * @param $pageText string
+ * @param $props bool|array
+ * @param $timestamp bool|string
+ * @param $user null|User
+ * @return bool
*/
function recordUpload2(
$oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
) {
+ wfProfileIn( __METHOD__ );
+
if ( is_null( $user ) ) {
global $wgUser;
$user = $wgUser;
}
$dbw = $this->repo->getMasterDB();
- $dbw->begin();
+ $dbw->begin( __METHOD__ );
if ( !$props ) {
+ wfProfileIn( __METHOD__ . '-getProps' );
$props = $this->repo->getFileProps( $this->getVirtualUrl() );
+ wfProfileOut( __METHOD__ . '-getProps' );
}
if ( $timestamp === false ) {
@@ -968,15 +1056,10 @@ class LocalFile extends File {
$props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
$this->setProps( $props );
- # Delete thumbnails
- $this->purgeThumbnails();
-
- # The file is already on its final location, remove it from the squid cache
- SquidUpdate::purge( array( $this->getURL() ) );
-
# Fail now if the file isn't there
if ( !$this->fileExists ) {
wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
+ wfProfileOut( __METHOD__ );
return false;
}
@@ -1005,15 +1088,12 @@ class LocalFile extends File {
__METHOD__,
'IGNORE'
);
-
if ( $dbw->affectedRows() == 0 ) {
- if ( $oldver == '' ) { // XXX
- # (bug 34993) publish() can displace the current file and yet fail to save
- # a new one. The next publish attempt will treat the file as a brand new file
- # and pass an empty $oldver. Allow this bogus value so we can displace the
- # `image` row to `oldimage`, leaving room for the new current file `image` row.
- #throw new MWException( "Empty oi_archive_name. Database and storage out of sync?" );
- }
+ # (bug 34993) Note: $oldver can be empty here, if the previous
+ # version of the file was broken. Allow registration of the new
+ # version to continue anyway, because that's better than having
+ # an image that's not fixable by user operations.
+
$reupload = true;
# Collision, this is an update of a file
# Insert previous contents into oldimage
@@ -1060,16 +1140,8 @@ class LocalFile extends File {
__METHOD__
);
} else {
- # This is a new file
- # Update the image count
- $dbw->begin( __METHOD__ );
- $dbw->update(
- 'site_stats',
- array( 'ss_images = ss_images+1' ),
- '*',
- __METHOD__
- );
- $dbw->commit( __METHOD__ );
+ # This is a new file, so update the image count
+ DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
}
$descTitle = $this->getTitle();
@@ -1079,14 +1151,17 @@ class LocalFile extends File {
# Add the log entry
$log = new LogPage( 'upload' );
$action = $reupload ? 'overwrite' : 'upload';
- $log->addEntry( $action, $descTitle, $comment, array(), $user );
+ $logId = $log->addEntry( $action, $descTitle, $comment, array(), $user );
+
+ wfProfileIn( __METHOD__ . '-edit' );
+ $exists = $descTitle->exists();
- if ( $descTitle->exists() ) {
+ if ( $exists ) {
# Create a null revision
$latest = $descTitle->getLatestRevID();
$nullRevision = Revision::newNullRevision(
$dbw,
- $descTitle->getArticleId(),
+ $descTitle->getArticleID(),
$log->getRcComment(),
false
);
@@ -1096,6 +1171,15 @@ class LocalFile extends File {
wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
$wikiPage->updateRevisionOn( $dbw, $nullRevision );
}
+ }
+
+ # Commit the transaction now, in case something goes wrong later
+ # The most important thing is that files don't get lost, especially archives
+ # NOTE: once we have support for nested transactions, the commit may be moved
+ # to after $wikiPage->doEdit has been called.
+ $dbw->commit( __METHOD__ );
+
+ if ( $exists ) {
# Invalidate the cache for the description page
$descTitle->invalidateCache();
$descTitle->purgeSquid();
@@ -1103,12 +1187,19 @@ class LocalFile extends File {
# New file; create the description page.
# There's already a log entry, so don't make a second RC entry
# Squid and file cache for the description page are purged by doEdit.
- $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC, false, $user );
+ $status = $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC, false, $user );
+
+ if ( isset( $status->value['revision'] ) ) { // XXX; doEdit() uses a transaction
+ $dbw->begin();
+ $dbw->update( 'logging',
+ array( 'log_page' => $status->value['revision']->getPage() ),
+ array( 'log_id' => $logId ),
+ __METHOD__
+ );
+ $dbw->commit(); // commit before anything bad can happen
+ }
}
-
- # Commit the transaction now, in case something goes wrong later
- # The most important thing is that files don't get lost, especially archives
- $dbw->commit();
+ wfProfileOut( __METHOD__ . '-edit' );
# Save to cache and purge the squid
# We shall not saveToCache before the commit since otherwise
@@ -1116,8 +1207,20 @@ class LocalFile extends File {
# which in fact doesn't really exist (bug 24978)
$this->saveToCache();
+ if ( $reupload ) {
+ # Delete old thumbnails
+ wfProfileIn( __METHOD__ . '-purge' );
+ $this->purgeThumbnails();
+ wfProfileOut( __METHOD__ . '-purge' );
+
+ # Remove the old file from the squid cache
+ SquidUpdate::purge( array( $this->getURL() ) );
+ }
+
# Hooks, hooks, the magic of hooks...
+ wfProfileIn( __METHOD__ . '-hooks' );
wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
+ wfProfileOut( __METHOD__ . '-hooks' );
# Invalidate cache for all pages using this file
$update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
@@ -1131,6 +1234,7 @@ class LocalFile extends File {
$update->doUpdate();
}
+ wfProfileOut( __METHOD__ );
return true;
}
@@ -1167,6 +1271,10 @@ class LocalFile extends File {
* archive name, or an empty string if it was a new file.
*/
function publishTo( $srcPath, $dstRel, $flags = 0 ) {
+ if ( $this->getRepo()->getReadOnlyReason() !== false ) {
+ return $this->readOnlyFatalStatus();
+ }
+
$this->lock(); // begin
$archiveName = wfTimestamp( TS_MW ) . '!'. $this->getName();
@@ -1203,20 +1311,26 @@ class LocalFile extends File {
* @return FileRepoStatus object.
*/
function move( $target ) {
- wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
- $this->lock(); // begin
+ if ( $this->getRepo()->getReadOnlyReason() !== false ) {
+ return $this->readOnlyFatalStatus();
+ }
+ wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
$batch = new LocalFileMoveBatch( $this, $target );
- $batch->addCurrent();
- $batch->addOlds();
+ $this->lock(); // begin
+ $batch->addCurrent();
+ $archiveNames = $batch->addOlds();
$status = $batch->execute();
+ $this->unlock(); // done
+
wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
$this->purgeEverything();
- $this->unlock(); // done
-
- if ( $status->isOk() ) {
+ foreach ( $archiveNames as $archiveName ) {
+ $this->purgeOldThumbnails( $archiveName );
+ }
+ if ( $status->isOK() ) {
// Now switch the object
$this->title = $target;
// Force regeneration of the name and hashpath
@@ -1242,30 +1356,27 @@ class LocalFile extends File {
* @return FileRepoStatus object.
*/
function delete( $reason, $suppress = false ) {
- $this->lock(); // begin
+ if ( $this->getRepo()->getReadOnlyReason() !== false ) {
+ return $this->readOnlyFatalStatus();
+ }
$batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
- $batch->addCurrent();
+ $this->lock(); // begin
+ $batch->addCurrent();
# Get old version relative paths
- $dbw = $this->repo->getMasterDB();
- $result = $dbw->select( 'oldimage',
- array( 'oi_archive_name' ),
- array( 'oi_name' => $this->getName() ) );
- foreach ( $result as $row ) {
- $batch->addOld( $row->oi_archive_name );
- $this->purgeOldThumbnails( $row->oi_archive_name );
- }
+ $archiveNames = $batch->addOlds();
$status = $batch->execute();
+ $this->unlock(); // done
- if ( $status->ok ) {
- // Update site_stats
- $site_stats = $dbw->tableName( 'site_stats' );
- $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
- $this->purgeEverything();
+ if ( $status->isOK() ) {
+ DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
}
- $this->unlock(); // done
+ $this->purgeEverything();
+ foreach ( $archiveNames as $archiveName ) {
+ $this->purgeOldThumbnails( $archiveName );
+ }
return $status;
}
@@ -1285,16 +1396,19 @@ class LocalFile extends File {
* @return FileRepoStatus object.
*/
function deleteOld( $archiveName, $reason, $suppress = false ) {
- $this->lock(); // begin
+ if ( $this->getRepo()->getReadOnlyReason() !== false ) {
+ return $this->readOnlyFatalStatus();
+ }
$batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
+
+ $this->lock(); // begin
$batch->addOld( $archiveName );
- $this->purgeOldThumbnails( $archiveName );
$status = $batch->execute();
-
$this->unlock(); // done
- if ( $status->ok ) {
+ $this->purgeOldThumbnails( $archiveName );
+ if ( $status->isOK() ) {
$this->purgeDescription();
$this->purgeHistory();
}
@@ -1308,30 +1422,32 @@ class LocalFile extends File {
*
* May throw database exceptions on error.
*
- * @param $versions set of record ids of deleted items to restore,
+ * @param $versions array set of record ids of deleted items to restore,
* or empty to restore all revisions.
* @param $unsuppress Boolean
* @return FileRepoStatus
*/
function restore( $versions = array(), $unsuppress = false ) {
+ if ( $this->getRepo()->getReadOnlyReason() !== false ) {
+ return $this->readOnlyFatalStatus();
+ }
+
$batch = new LocalFileRestoreBatch( $this, $unsuppress );
+ $this->lock(); // begin
if ( !$versions ) {
$batch->addAll();
} else {
$batch->addIds( $versions );
}
-
$status = $batch->execute();
-
- if ( !$status->isGood() ) {
- return $status;
+ if ( $status->isGood() ) {
+ $cleanupStatus = $batch->cleanup();
+ $cleanupStatus->successCount = 0;
+ $cleanupStatus->failCount = 0;
+ $status->merge( $cleanupStatus );
}
-
- $cleanupStatus = $batch->cleanup();
- $cleanupStatus->successCount = 0;
- $cleanupStatus->failCount = 0;
- $status->merge( $cleanupStatus );
+ $this->unlock(); // done
return $status;
}
@@ -1343,6 +1459,7 @@ class LocalFile extends File {
/**
* Get the URL of the file description page.
+ * @return String
*/
function getDescriptionUrl() {
return $this->title->getLocalUrl();
@@ -1352,10 +1469,11 @@ class LocalFile extends File {
* 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.
+ * @return bool|mixed
*/
function getDescriptionText() {
global $wgParser;
- $revision = Revision::newFromTitle( $this->title );
+ $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
if ( !$revision ) return false;
$text = $revision->getText();
if ( !$text ) return false;
@@ -1363,16 +1481,33 @@ class LocalFile extends File {
return $pout->getText();
}
- function getDescription() {
+ /**
+ * @return string
+ */
+ function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
$this->load();
- return $this->description;
+ if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
+ return '';
+ } elseif ( $audience == self::FOR_THIS_USER
+ && !$this->userCan( self::DELETED_COMMENT, $user ) )
+ {
+ return '';
+ } else {
+ return $this->description;
+ }
}
+ /**
+ * @return bool|string
+ */
function getTimestamp() {
$this->load();
return $this->timestamp;
}
+ /**
+ * @return string
+ */
function getSha1() {
$this->load();
// Initialise now if necessary
@@ -1396,6 +1531,14 @@ class LocalFile extends File {
}
/**
+ * @return bool
+ */
+ function isCacheable() {
+ $this->load();
+ return strlen( $this->metadata ) <= self::CACHE_FIELD_MAX_LEN; // avoid OOMs
+ }
+
+ /**
* Start a transaction and lock the image for update
* Increments a reference counter if the lock is already held
* @return boolean True if the image exists, false otherwise
@@ -1404,11 +1547,12 @@ class LocalFile extends File {
$dbw = $this->repo->getMasterDB();
if ( !$this->locked ) {
- $dbw->begin();
+ $dbw->begin( __METHOD__ );
$this->locked++;
}
- return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
+ return $dbw->selectField( 'image', '1',
+ array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
}
/**
@@ -1420,7 +1564,7 @@ class LocalFile extends File {
--$this->locked;
if ( !$this->locked ) {
$dbw = $this->repo->getMasterDB();
- $dbw->commit();
+ $dbw->commit( __METHOD__ );
}
}
}
@@ -1431,7 +1575,15 @@ class LocalFile extends File {
function unlockAndRollback() {
$this->locked = false;
$dbw = $this->repo->getMasterDB();
- $dbw->rollback();
+ $dbw->rollback( __METHOD__ );
+ }
+
+ /**
+ * @return Status
+ */
+ protected function readOnlyFatalStatus() {
+ return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
+ $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
}
} // LocalFile class
@@ -1451,6 +1603,11 @@ class LocalFileDeleteBatch {
var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
var $status;
+ /**
+ * @param $file File
+ * @param $reason string
+ * @param $suppress bool
+ */
function __construct( File $file, $reason = '', $suppress = false ) {
$this->file = $file;
$this->reason = $reason;
@@ -1462,11 +1619,39 @@ class LocalFileDeleteBatch {
$this->srcRels['.'] = $this->file->getRel();
}
+ /**
+ * @param $oldName string
+ */
function addOld( $oldName ) {
$this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
$this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
}
+ /**
+ * Add the old versions of the image to the batch
+ * @return Array List of archive names from old versions
+ */
+ function addOlds() {
+ $archiveNames = array();
+
+ $dbw = $this->file->repo->getMasterDB();
+ $result = $dbw->select( 'oldimage',
+ array( 'oi_archive_name' ),
+ array( 'oi_name' => $this->file->getName() ),
+ __METHOD__
+ );
+
+ foreach ( $result as $row ) {
+ $this->addOld( $row->oi_archive_name );
+ $archiveNames[] = $row->oi_archive_name;
+ }
+
+ return $archiveNames;
+ }
+
+ /**
+ * @return array
+ */
function getOldRels() {
if ( !isset( $this->srcRels['.'] ) ) {
$oldRels =& $this->srcRels;
@@ -1480,6 +1665,9 @@ class LocalFileDeleteBatch {
return array( $oldRels, $deleteCurrent );
}
+ /**
+ * @return array
+ */
protected function getHashes() {
$hashes = array();
list( $oldRels, $deleteCurrent ) = $this->getOldRels();
@@ -1601,7 +1789,7 @@ class LocalFileDeleteBatch {
'fa_deleted_user' => $encUserId,
'fa_deleted_timestamp' => $encTimestamp,
'fa_deleted_reason' => $encReason,
- 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
+ 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
'fa_name' => 'oi_name',
'fa_archive_name' => 'oi_archive_name',
@@ -1617,7 +1805,6 @@ class LocalFileDeleteBatch {
'fa_user' => 'oi_user',
'fa_user_text' => 'oi_user_text',
'fa_timestamp' => 'oi_timestamp',
- 'fa_deleted' => $bitfield
), $where, __METHOD__ );
}
}
@@ -1641,9 +1828,9 @@ class LocalFileDeleteBatch {
/**
* Run the transaction
+ * @return FileRepoStatus
*/
function execute() {
- global $wgUseSquid;
wfProfileIn( __METHOD__ );
$this->file->lock();
@@ -1699,7 +1886,7 @@ class LocalFileDeleteBatch {
$this->status->merge( $status );
}
- if ( !$this->status->ok ) {
+ if ( !$this->status->isOK() ) {
// Critical file deletion error
// Roll back inserts, release lock and abort
// TODO: delete the defunct filearchive rows if we are using a non-transactional DB
@@ -1708,17 +1895,6 @@ class LocalFileDeleteBatch {
return $this->status;
}
- // Purge squid
- if ( $wgUseSquid ) {
- $urls = array();
-
- foreach ( $this->srcRels as $srcRel ) {
- $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
- $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
- }
- SquidUpdate::purge( $urls );
- }
-
// Delete image/oldimage rows
$this->doDBDeletes();
@@ -1731,6 +1907,8 @@ class LocalFileDeleteBatch {
/**
* Removes non-existent files from a deletion batch.
+ * @param $batch array
+ * @return array
*/
function removeNonexistentFiles( $batch ) {
$files = $newBatch = array();
@@ -1740,7 +1918,7 @@ class LocalFileDeleteBatch {
$files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
}
- $result = $this->file->repo->fileExistsBatch( $files, FileRepo::FILES_ONLY );
+ $result = $this->file->repo->fileExistsBatch( $files );
foreach ( $batch as $batchItem ) {
if ( $result[$batchItem[0]] ) {
@@ -1766,6 +1944,10 @@ class LocalFileRestoreBatch {
var $cleanupBatch, $ids, $all, $unsuppress = false;
+ /**
+ * @param $file File
+ * @param $unsuppress bool
+ */
function __construct( File $file, $unsuppress = false ) {
$this->file = $file;
$this->cleanupBatch = $this->ids = array();
@@ -1800,6 +1982,7 @@ class LocalFileRestoreBatch {
* rows and there's no need to keep the image row locked while it's acquiring those locks
* The caller may have its own transaction open.
* So we save the batch and let the caller call cleanup()
+ * @return FileRepoStatus
*/
function execute() {
global $wgLang;
@@ -2003,9 +2186,7 @@ class LocalFileRestoreBatch {
if ( !$exists ) {
wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
- // Update site_stats
- $site_stats = $dbw->tableName( 'site_stats' );
- $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
+ DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
$this->file->purgeEverything();
} else {
@@ -2022,13 +2203,16 @@ class LocalFileRestoreBatch {
/**
* Removes non-existent files from a store batch.
+ * @param $triplets array
+ * @return array
*/
function removeNonexistentFiles( $triplets ) {
$files = $filteredTriplets = array();
- foreach ( $triplets as $file )
+ foreach ( $triplets as $file ) {
$files[$file[0]] = $file[0];
+ }
- $result = $this->file->repo->fileExistsBatch( $files, FileRepo::FILES_ONLY );
+ $result = $this->file->repo->fileExistsBatch( $files );
foreach ( $triplets as $file ) {
if ( $result[$file[0]] ) {
@@ -2041,6 +2225,8 @@ class LocalFileRestoreBatch {
/**
* Removes non-existent files from a cleanup batch.
+ * @param $batch array
+ * @return array
*/
function removeNonexistentFromCleanup( $batch ) {
$files = $newBatch = array();
@@ -2051,7 +2237,7 @@ class LocalFileRestoreBatch {
rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
}
- $result = $repo->fileExistsBatch( $files, FileRepo::FILES_ONLY );
+ $result = $repo->fileExistsBatch( $files );
foreach ( $batch as $file ) {
if ( $result[$file] ) {
@@ -2065,6 +2251,7 @@ class LocalFileRestoreBatch {
/**
* Delete unused files in the deleted zone.
* This should be called from outside the transaction in which execute() was called.
+ * @return FileRepoStatus|void
*/
function cleanup() {
if ( !$this->cleanupBatch ) {
@@ -2109,7 +2296,7 @@ class LocalFileRestoreBatch {
class LocalFileMoveBatch {
/**
- * @var File
+ * @var LocalFile
*/
var $file;
@@ -2118,8 +2305,17 @@ class LocalFileMoveBatch {
*/
var $target;
- var $cur, $olds, $oldCount, $archive, $db;
+ var $cur, $olds, $oldCount, $archive;
+ /**
+ * @var DatabaseBase
+ */
+ var $db;
+
+ /**
+ * @param File $file
+ * @param Title $target
+ */
function __construct( File $file, Title $target ) {
$this->file = $file;
$this->target = $target;
@@ -2129,7 +2325,7 @@ class LocalFileMoveBatch {
$this->newName = $this->file->repo->getNameFromTitle( $this->target );
$this->oldRel = $this->oldHash . $this->oldName;
$this->newRel = $this->newHash . $this->newName;
- $this->db = $file->repo->getMasterDb();
+ $this->db = $file->getRepo()->getMasterDb();
}
/**
@@ -2141,11 +2337,13 @@ class LocalFileMoveBatch {
/**
* Add the old versions of the image to the batch
+ * @return Array List of archive names from old versions
*/
function addOlds() {
$archiveBase = 'archive';
$this->olds = array();
$this->oldCount = 0;
+ $archiveNames = array();
$result = $this->db->select( 'oldimage',
array( 'oi_archive_name', 'oi_deleted' ),
@@ -2154,6 +2352,7 @@ class LocalFileMoveBatch {
);
foreach ( $result as $row ) {
+ $archiveNames[] = $row->oi_archive_name;
$oldName = $row->oi_archive_name;
$bits = explode( '!', $oldName, 2 );
@@ -2181,39 +2380,49 @@ class LocalFileMoveBatch {
"{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
);
}
+
+ return $archiveNames;
}
/**
* Perform the move.
+ * @return FileRepoStatus
*/
function execute() {
$repo = $this->file->repo;
$status = $repo->newGood();
- $triplets = $this->getMoveTriplets();
+ $triplets = $this->getMoveTriplets();
$triplets = $this->removeNonexistentFiles( $triplets );
- // Copy the files into their new location
- $statusMove = $repo->storeBatch( $triplets );
+ $this->file->lock(); // begin
+ // Rename the file versions metadata in the DB.
+ // This implicitly locks the destination file, which avoids race conditions.
+ // If we moved the files from A -> C before DB updates, another process could
+ // move files from B -> C at this point, causing storeBatch() to fail and thus
+ // cleanupTarget() to trigger. It would delete the C files and cause data loss.
+ $statusDb = $this->doDBUpdates();
+ if ( !$statusDb->isGood() ) {
+ $this->file->unlockAndRollback();
+ $statusDb->ok = false;
+ return $statusDb;
+ }
+ wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
+
+ // Copy the files into their new location.
+ // If a prior process fataled copying or cleaning up files we tolerate any
+ // of the existing files if they are identical to the ones being stored.
+ $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
if ( !$statusMove->isGood() ) {
- wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
+ // Delete any files copied over (while the destination is still locked)
$this->cleanupTarget( $triplets );
+ $this->file->unlockAndRollback(); // unlocks the destination
+ wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
$statusMove->ok = false;
return $statusMove;
}
-
- $this->db->begin();
- $statusDb = $this->doDBUpdates();
- wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
- if ( !$statusDb->isGood() ) {
- $this->db->rollback();
- // Something went wrong with the DB updates, so remove the target files
- $this->cleanupTarget( $triplets );
- $statusDb->ok = false;
- return $statusDb;
- }
- $this->db->commit();
+ $this->file->unlock(); // done
// Everything went ok, remove the source files
$this->cleanupSource( $triplets );
@@ -2256,7 +2465,8 @@ class LocalFileMoveBatch {
'oldimage',
array(
'oi_name' => $this->newName,
- 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
+ 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
+ $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
),
array( 'oi_name' => $this->oldName ),
__METHOD__
@@ -2265,7 +2475,10 @@ class LocalFileMoveBatch {
$affected = $dbw->affectedRows();
$total = $this->oldCount;
$status->successCount += $affected;
- $status->failCount += $total - $affected;
+ // Bug 34934: $total is based on files that actually exist.
+ // There may be more DB rows than such files, in which case $affected
+ // can be greater than $total. We use max() to avoid negatives here.
+ $status->failCount += max( 0, $total - $affected );
if ( $status->failCount ) {
$status->error( 'imageinvalidfilename' );
}
@@ -2275,6 +2488,7 @@ class LocalFileMoveBatch {
/**
* Generate triplets for FileRepo::storeBatch().
+ * @return array
*/
function getMoveTriplets() {
$moves = array_merge( array( $this->cur ), $this->olds );
@@ -2292,6 +2506,8 @@ class LocalFileMoveBatch {
/**
* Removes non-existent files from move batch.
+ * @param $triplets array
+ * @return array
*/
function removeNonexistentFiles( $triplets ) {
$files = array();
@@ -2300,7 +2516,7 @@ class LocalFileMoveBatch {
$files[$file[0]] = $file[0];
}
- $result = $this->file->repo->fileExistsBatch( $files, FileRepo::FILES_ONLY );
+ $result = $this->file->repo->fileExistsBatch( $files );
$filteredTriplets = array();
foreach ( $triplets as $file ) {
@@ -2322,6 +2538,7 @@ class LocalFileMoveBatch {
// Create dest pairs from the triplets
$pairs = array();
foreach ( $triplets as $triplet ) {
+ // $triplet: (old source virtual URL, dst zone, dest rel)
$pairs[] = array( $triplet[1], $triplet[2] );
}
diff --git a/includes/filerepo/file/OldLocalFile.php b/includes/filerepo/file/OldLocalFile.php
index ebd83c4d..40d7dca7 100644
--- a/includes/filerepo/file/OldLocalFile.php
+++ b/includes/filerepo/file/OldLocalFile.php
@@ -1,6 +1,21 @@
<?php
/**
- * Old file in the oldimage table
+ * Old file in the oldimage table.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileAbstraction
@@ -17,6 +32,13 @@ class OldLocalFile extends LocalFile {
const CACHE_VERSION = 1;
const MAX_CACHE_ROWS = 20;
+ /**
+ * @param $title Title
+ * @param $repo FileRepo
+ * @param $time null
+ * @return OldLocalFile
+ * @throws MWException
+ */
static function newFromTitle( $title, $repo, $time = null ) {
# The null default value is only here to avoid an E_STRICT
if ( $time === null ) {
@@ -25,10 +47,21 @@ class OldLocalFile extends LocalFile {
return new self( $title, $repo, $time, null );
}
+ /**
+ * @param $title Title
+ * @param $repo FileRepo
+ * @param $archiveName
+ * @return OldLocalFile
+ */
static function newFromArchiveName( $title, $repo, $archiveName ) {
return new self( $title, $repo, null, $archiveName );
}
+ /**
+ * @param $row
+ * @param $repo FileRepo
+ * @return OldLocalFile
+ */
static function newFromRow( $row, $repo ) {
$title = Title::makeTitle( NS_FILE, $row->oi_name );
$file = new self( $title, $repo, null, $row->oi_archive_name );
@@ -61,9 +94,10 @@ class OldLocalFile extends LocalFile {
return false;
}
}
-
+
/**
* Fields in the oldimage table
+ * @return array
*/
static function selectFields() {
return array(
@@ -91,6 +125,7 @@ class OldLocalFile extends LocalFile {
* @param $repo FileRepo
* @param $time String: timestamp or null to load by archive name
* @param $archiveName String: archive name or null to load by timestamp
+ * @throws MWException
*/
function __construct( $title, $repo, $time, $archiveName ) {
parent::__construct( $title, $repo );
@@ -101,10 +136,16 @@ class OldLocalFile extends LocalFile {
}
}
+ /**
+ * @return bool
+ */
function getCacheKey() {
return false;
}
+ /**
+ * @return String
+ */
function getArchiveName() {
if ( !isset( $this->archive_name ) ) {
$this->load();
@@ -112,10 +153,16 @@ class OldLocalFile extends LocalFile {
return $this->archive_name;
}
+ /**
+ * @return bool
+ */
function isOld() {
return true;
}
+ /**
+ * @return bool
+ */
function isVisible() {
return $this->exists() && !$this->isDeleted(File::DELETED_FILE);
}
@@ -140,6 +187,10 @@ class OldLocalFile extends LocalFile {
wfProfileOut( __METHOD__ );
}
+ /**
+ * @param $prefix string
+ * @return array
+ */
function getCacheFields( $prefix = 'img_' ) {
$fields = parent::getCacheFields( $prefix );
$fields[] = $prefix . 'archive_name';
@@ -147,10 +198,16 @@ class OldLocalFile extends LocalFile {
return $fields;
}
+ /**
+ * @return string
+ */
function getRel() {
return 'archive/' . $this->getHashPath() . $this->getArchiveName();
}
+ /**
+ * @return string
+ */
function getUrlRel() {
return 'archive/' . $this->getHashPath() . rawurlencode( $this->getArchiveName() );
}
@@ -172,14 +229,15 @@ class OldLocalFile extends LocalFile {
wfDebug(__METHOD__.': upgrading '.$this->archive_name." to the current schema\n");
$dbw->update( 'oldimage',
array(
- 'oi_width' => $this->width,
- 'oi_height' => $this->height,
- 'oi_bits' => $this->bits,
+ 'oi_size' => $this->size, // sanity
+ 'oi_width' => $this->width,
+ 'oi_height' => $this->height,
+ 'oi_bits' => $this->bits,
'oi_media_type' => $this->media_type,
'oi_major_mime' => $major,
'oi_minor_mime' => $minor,
- 'oi_metadata' => $this->metadata,
- 'oi_sha1' => $this->sha1,
+ 'oi_metadata' => $this->metadata,
+ 'oi_sha1' => $this->sha1,
), array(
'oi_name' => $this->getName(),
'oi_archive_name' => $this->archive_name ),
@@ -219,47 +277,52 @@ class OldLocalFile extends LocalFile {
$this->load();
return Revision::userCanBitfield( $this->deleted, $field, $user );
}
-
+
/**
* Upload a file directly into archive. Generally for Special:Import.
- *
+ *
* @param $srcPath string File system path of the source file
- * @param $archiveName string Full archive name of the file, in the form
- * $timestamp!$filename, where $filename must match $this->getName()
+ * @param $archiveName string Full archive name of the file, in the form
+ * $timestamp!$filename, where $filename must match $this->getName()
*
+ * @param $timestamp string
+ * @param $comment string
+ * @param $user
+ * @param $flags int
* @return FileRepoStatus
*/
function uploadOld( $srcPath, $archiveName, $timestamp, $comment, $user, $flags = 0 ) {
$this->lock();
-
+
$dstRel = 'archive/' . $this->getHashPath() . $archiveName;
$status = $this->publishTo( $srcPath, $dstRel,
$flags & File::DELETE_SOURCE ? FileRepo::DELETE_SOURCE : 0
);
-
+
if ( $status->isGood() ) {
if ( !$this->recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user ) ) {
$status->fatal( 'filenotfound', $srcPath );
}
}
-
+
$this->unlock();
-
+
return $status;
}
-
+
/**
* Record a file upload in the oldimage table, without adding log entries.
- *
+ *
* @param $srcPath string File system path to the source file
* @param $archiveName string The archive name of the file
+ * @param $timestamp string
* @param $comment string Upload comment
* @param $user User User who did this upload
* @return bool
*/
function recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user ) {
$dbw = $this->repo->getMasterDB();
- $dbw->begin();
+ $dbw->begin( __METHOD__ );
$dstPath = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
$props = $this->repo->getFileProps( $dstPath );
@@ -287,9 +350,9 @@ class OldLocalFile extends LocalFile {
), __METHOD__
);
- $dbw->commit();
+ $dbw->commit( __METHOD__ );
return true;
}
-
+
}
diff --git a/includes/filerepo/file/UnregisteredLocalFile.php b/includes/filerepo/file/UnregisteredLocalFile.php
index cd9d3d02..8d4a3f88 100644
--- a/includes/filerepo/file/UnregisteredLocalFile.php
+++ b/includes/filerepo/file/UnregisteredLocalFile.php
@@ -1,6 +1,21 @@
<?php
/**
- * File without associated database record
+ * File without associated database record.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup FileAbstraction
@@ -19,7 +34,7 @@
* @ingroup FileAbstraction
*/
class UnregisteredLocalFile extends File {
- var $title, $path, $mime, $dims;
+ var $title, $path, $mime, $dims, $metadata;
/**
* @var MediaHandler
@@ -47,12 +62,12 @@ class UnregisteredLocalFile extends File {
/**
* Create an UnregisteredLocalFile based on a path or a (title,repo) pair.
* A FileRepo object is not required here, unlike most other File classes.
- *
+ *
* @throws MWException
- * @param $title Title|false
- * @param $repo FileRepo
- * @param $path string
- * @param $mime string
+ * @param $title Title|bool
+ * @param $repo FileRepo|bool
+ * @param $path string|bool
+ * @param $mime string|bool
*/
function __construct( $title = false, $repo = false, $path = false, $mime = false ) {
if ( !( $title && $repo ) && !$path ) {
@@ -79,6 +94,10 @@ class UnregisteredLocalFile extends File {
$this->dims = array();
}
+ /**
+ * @param $page int
+ * @return bool
+ */
private function cachePageDimensions( $page = 1 ) {
if ( !isset( $this->dims[$page] ) ) {
if ( !$this->getHandler() ) {
@@ -89,16 +108,27 @@ class UnregisteredLocalFile extends File {
return $this->dims[$page];
}
+ /**
+ * @param $page int
+ * @return number
+ */
function getWidth( $page = 1 ) {
$dim = $this->cachePageDimensions( $page );
return $dim['width'];
}
+ /**
+ * @param $page int
+ * @return number
+ */
function getHeight( $page = 1 ) {
$dim = $this->cachePageDimensions( $page );
return $dim['height'];
}
+ /**
+ * @return bool|string
+ */
function getMimeType() {
if ( !isset( $this->mime ) ) {
$magic = MimeMagic::singleton();
@@ -107,6 +137,10 @@ class UnregisteredLocalFile extends File {
return $this->mime;
}
+ /**
+ * @param $filename String
+ * @return Array|bool
+ */
function getImageSize( $filename ) {
if ( !$this->getHandler() ) {
return false;
@@ -114,6 +148,9 @@ class UnregisteredLocalFile extends File {
return $this->handler->getImageSize( $this, $this->getLocalRefPath() );
}
+ /**
+ * @return bool
+ */
function getMetadata() {
if ( !isset( $this->metadata ) ) {
if ( !$this->getHandler() ) {
@@ -125,6 +162,9 @@ class UnregisteredLocalFile extends File {
return $this->metadata;
}
+ /**
+ * @return bool|string
+ */
function getURL() {
if ( $this->repo ) {
return $this->repo->getZoneUrl( 'public' ) . '/' .
@@ -134,6 +174,9 @@ class UnregisteredLocalFile extends File {
}
}
+ /**
+ * @return bool|int
+ */
function getSize() {
$this->assertRepoDefined();
$props = $this->repo->getFileProps( $this->path );