/includes/filerepo/file/LocalFile.php
PHP | 2561 lines | 1549 code | 339 blank | 673 comment | 188 complexity | cc9f3983c30f93a58e5753c625b88505 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * 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
- */
- /**
- * Bump this number when serialized cache records may be incompatible.
- */
- define( 'MW_FILE_VERSION', 8 );
- /**
- * Class to represent a local file in the wiki's own database
- *
- * Provides methods to retrieve paths (physical, logical, URL),
- * to generate image thumbnails or for uploading.
- *
- * Note that only the repo object knows what its file class is called. You should
- * never name a file class explictly outside of the repo class. Instead use the
- * repo's factory functions to generate file objects, for example:
- *
- * RepoGroup::singleton()->getLocalRepo()->newFile($title);
- *
- * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
- * in most cases.
- *
- * @ingroup FileAbstraction
- */
- class LocalFile extends File {
- const CACHE_FIELD_MAX_LEN = 1000;
- /**#@+
- * @private
- */
- var
- $fileExists, # does the file exist on disk? (loadFromXxx)
- $historyLine, # Number of line to return by nextHistoryLine() (constructor)
- $historyRes, # result of the query for the file's history (nextHistoryLine)
- $width, # \
- $height, # |
- $bits, # --- returned by getimagesize (loadFromXxx)
- $attr, # /
- $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
- $mime, # MIME type, determined by MimeMagic::guessMimeType
- $major_mime, # Major mime type
- $minor_mime, # Minor mime type
- $size, # Size in bytes (loadFromXxx)
- $metadata, # Handler-specific metadata
- $timestamp, # Upload timestamp
- $sha1, # SHA-1 base 36 content hash
- $user, $user_text, # User, who uploaded the file
- $description, # Description of current revision of the file
- $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
- $upgraded, # Whether the row was upgraded on load
- $locked, # True if the image row is locked
- $missing, # True if file is not present in file system. Not to be cached in memcached
- $deleted; # Bitfield akin to rev_deleted
- /**#@-*/
- /**
- * @var LocalRepo
- */
- var $repo;
- protected $repoClass = 'LocalRepo';
- /**
- * Create a LocalFile from a title
- * Do not call this except from inside a repo class.
- *
- * Note: $unused param is only here to avoid an E_STRICT
- *
- * @param $title
- * @param $repo
- * @param $unused
- *
- * @return LocalFile
- */
- static function newFromTitle( $title, $repo, $unused = null ) {
- return new self( $title, $repo );
- }
- /**
- * Create a LocalFile from a title
- * Do not call this except from inside a repo class.
- *
- * @param $row
- * @param $repo
- *
- * @return LocalFile
- */
- static function newFromRow( $row, $repo ) {
- $title = Title::makeTitle( NS_FILE, $row->img_name );
- $file = new self( $title, $repo );
- $file->loadFromRow( $row );
- return $file;
- }
- /**
- * Create a LocalFile from a SHA-1 key
- * Do not call this except from inside a repo class.
- *
- * @param $sha1 string base-36 SHA-1
- * @param $repo LocalRepo
- * @param string|bool $timestamp MW_timestamp (optional)
- *
- * @return bool|LocalFile
- */
- static function newFromKey( $sha1, $repo, $timestamp = false ) {
- $dbr = $repo->getSlaveDB();
- $conds = array( 'img_sha1' => $sha1 );
- if ( $timestamp ) {
- $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
- }
- $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
- if ( $row ) {
- return self::newFromRow( $row, $repo );
- } else {
- return false;
- }
- }
- /**
- * Fields in the image table
- * @return array
- */
- static function selectFields() {
- return array(
- 'img_name',
- 'img_size',
- 'img_width',
- 'img_height',
- 'img_metadata',
- 'img_bits',
- 'img_media_type',
- 'img_major_mime',
- 'img_minor_mime',
- 'img_description',
- 'img_user',
- 'img_user_text',
- 'img_timestamp',
- 'img_sha1',
- );
- }
- /**
- * Constructor.
- * Do not call this except from inside a repo class.
- */
- function __construct( $title, $repo ) {
- parent::__construct( $title, $repo );
- $this->metadata = '';
- $this->historyLine = 0;
- $this->historyRes = null;
- $this->dataLoaded = false;
- $this->assertRepoDefined();
- $this->assertTitleDefined();
- }
- /**
- * 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() );
- return $this->repo->getSharedCacheKey( 'file', $hashedName );
- }
- /**
- * Try to load file metadata from memcached. Returns true on success.
- * @return bool
- */
- function loadFromCache() {
- global $wgMemc;
- wfProfileIn( __METHOD__ );
- $this->dataLoaded = false;
- $key = $this->getCacheKey();
- if ( !$key ) {
- wfProfileOut( __METHOD__ );
- return false;
- }
- $cachedValues = $wgMemc->get( $key );
- // Check if the key existed and belongs to this version of MediaWiki
- if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
- wfDebug( "Pulling file metadata from cache key $key\n" );
- $this->fileExists = $cachedValues['fileExists'];
- if ( $this->fileExists ) {
- $this->setProps( $cachedValues );
- }
- $this->dataLoaded = true;
- }
- if ( $this->dataLoaded ) {
- wfIncrStats( 'image_cache_hit' );
- } else {
- wfIncrStats( 'image_cache_miss' );
- }
- wfProfileOut( __METHOD__ );
- return $this->dataLoaded;
- }
- /**
- * Save the file metadata to memcached
- */
- function saveToCache() {
- global $wgMemc;
- $this->load();
- $key = $this->getCacheKey();
- if ( !$key ) {
- return;
- }
- $fields = $this->getCacheFields( '' );
- $cache = array( 'version' => MW_FILE_VERSION );
- $cache['fileExists'] = $this->fileExists;
- if ( $this->fileExists ) {
- foreach ( $fields as $field ) {
- $cache[$field] = $this->$field;
- }
- }
- $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
- }
- /**
- * Load metadata from the file itself
- */
- function loadFromFile() {
- $props = $this->repo->getFileProps( $this->getVirtualUrl() );
- $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' );
- static $results = array();
- if ( $prefix == '' ) {
- return $fields;
- }
- if ( !isset( $results[$prefix] ) ) {
- $prefixedFields = array();
- foreach ( $fields as $field ) {
- $prefixedFields[] = $prefix . $field;
- }
- $results[$prefix] = $prefixedFields;
- }
- return $results[$prefix];
- }
- /**
- * Load file metadata from the DB
- */
- function loadFromDB() {
- # Polymorphic function name to distinguish foreign and local fetches
- $fname = get_class( $this ) . '::' . __FUNCTION__;
- wfProfileIn( $fname );
- # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
- $this->dataLoaded = true;
- $dbr = $this->repo->getMasterDB();
- $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
- array( 'img_name' => $this->getName() ), $fname );
- if ( $row ) {
- $this->loadFromRow( $row );
- } else {
- $this->fileExists = false;
- }
- wfProfileOut( $fname );
- }
- /**
- * 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;
- $prefixLength = strlen( $prefix );
- // Sanity check prefix once
- if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
- throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
- }
- $decoded = array();
- foreach ( $array as $name => $value ) {
- $decoded[substr( $name, $prefixLength )] = $value;
- }
- $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
- if ( empty( $decoded['major_mime'] ) ) {
- $decoded['mime'] = 'unknown/unknown';
- } else {
- if ( !$decoded['minor_mime'] ) {
- $decoded['minor_mime'] = 'unknown';
- }
- $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
- }
- # Trim zero padding from char/binary field
- $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
- return $decoded;
- }
- /**
- * Load file metadata from a DB result row
- */
- function loadFromRow( $row, $prefix = 'img_' ) {
- $this->dataLoaded = true;
- $array = $this->decodeRow( $row, $prefix );
- foreach ( $array as $name => $value ) {
- $this->$name = $value;
- }
- $this->fileExists = true;
- $this->maybeUpgradeRow();
- }
- /**
- * Load file metadata from cache or DB, unless already loaded
- */
- function load() {
- if ( !$this->dataLoaded ) {
- if ( !$this->loadFromCache() ) {
- $this->loadFromDB();
- $this->saveToCache();
- }
- $this->dataLoaded = true;
- }
- }
- /**
- * Upgrade a row if it needs it
- */
- function maybeUpgradeRow() {
- global $wgUpdateCompatibleMetadata;
- if ( wfReadOnly() ) {
- return;
- }
- if ( is_null( $this->media_type ) ||
- $this->mime == 'image/svg'
- ) {
- $this->upgradeRow();
- $this->upgraded = true;
- } else {
- $handler = $this->getHandler();
- if ( $handler ) {
- $validity = $handler->isMetadataValid( $this, $this->metadata );
- if ( $validity === MediaHandler::METADATA_BAD
- || ( $validity === MediaHandler::METADATA_COMPATIBLE && $wgUpdateCompatibleMetadata )
- ) {
- $this->upgradeRow();
- $this->upgraded = true;
- }
- }
- }
- }
- function getUpgraded() {
- return $this->upgraded;
- }
- /**
- * Fix assorted version-related problems with the image row by reloading it from the file
- */
- function upgradeRow() {
- wfProfileIn( __METHOD__ );
- $this->lock(); // begin
- $this->loadFromFile();
- # Don't destroy file info of missing files
- if ( !$this->fileExists ) {
- wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
- wfProfileOut( __METHOD__ );
- return;
- }
- $dbw = $this->repo->getMasterDB();
- list( $major, $minor ) = self::splitMime( $this->mime );
- if ( wfReadOnly() ) {
- wfProfileOut( __METHOD__ );
- return;
- }
- wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
- $dbw->update( 'image',
- array(
- 'img_size' => $this->size, // sanity
- 'img_width' => $this->width,
- 'img_height' => $this->height,
- 'img_bits' => $this->bits,
- 'img_media_type' => $this->media_type,
- 'img_major_mime' => $major,
- 'img_minor_mime' => $minor,
- 'img_metadata' => $this->metadata,
- 'img_sha1' => $this->sha1,
- ),
- array( 'img_name' => $this->getName() ),
- __METHOD__
- );
- $this->saveToCache();
- $this->unlock(); // done
- wfProfileOut( __METHOD__ );
- }
- /**
- * Set properties in this object to be equal to those given in the
- * associative array $info. Only cacheable fields can be set.
- *
- * If 'mime' is given, it will be split into major_mime/minor_mime.
- * If major_mime/minor_mime are given, $this->mime will also be set.
- */
- function setProps( $info ) {
- $this->dataLoaded = true;
- $fields = $this->getCacheFields( '' );
- $fields[] = 'fileExists';
- foreach ( $fields as $field ) {
- if ( isset( $info[$field] ) ) {
- $this->$field = $info[$field];
- }
- }
- // Fix up mime fields
- if ( isset( $info['major_mime'] ) ) {
- $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
- } elseif ( isset( $info['mime'] ) ) {
- $this->mime = $info['mime'];
- list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
- }
- }
- /** splitMime inherited */
- /** getName inherited */
- /** getTitle inherited */
- /** getURL inherited */
- /** getViewURL inherited */
- /** getPath inherited */
- /** isVisible inhereted */
- /**
- * @return bool
- */
- function isMissing() {
- if ( $this->missing === null ) {
- list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
- $this->missing = !$fileExists;
- }
- return $this->missing;
- }
- /**
- * Return the width of the image
- *
- * @param $page int
- * @return bool|int Returns false on error
- */
- public function getWidth( $page = 1 ) {
- $this->load();
- if ( $this->isMultipage() ) {
- $dim = $this->getHandler()->getPageDimensions( $this, $page );
- if ( $dim ) {
- return $dim['width'];
- } else {
- return false;
- }
- } else {
- return $this->width;
- }
- }
- /**
- * Return the height of the image
- *
- * @param $page int
- * @return bool|int Returns false on error
- */
- public function getHeight( $page = 1 ) {
- $this->load();
- if ( $this->isMultipage() ) {
- $dim = $this->getHandler()->getPageDimensions( $this, $page );
- if ( $dim ) {
- return $dim['height'];
- } else {
- return false;
- }
- } else {
- return $this->height;
- }
- }
- /**
- * 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();
- if ( $type == 'text' ) {
- return $this->user_text;
- } elseif ( $type == 'id' ) {
- return $this->user;
- }
- }
- /**
- * Get handler-specific metadata
- * @return string
- */
- function getMetadata() {
- $this->load();
- return $this->metadata;
- }
- /**
- * @return int
- */
- function getBitDepth() {
- $this->load();
- return $this->bits;
- }
- /**
- * Return the size of the image file, in bytes
- * @return int
- */
- public function getSize() {
- $this->load();
- return $this->size;
- }
- /**
- * Returns the mime type of the file.
- * @return string
- */
- function getMimeType() {
- $this->load();
- return $this->mime;
- }
- /**
- * 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();
- return $this->media_type;
- }
- /** canRender inherited */
- /** mustRender inherited */
- /** allowInlineDisplay inherited */
- /** isSafeFile inherited */
- /** isTrustedFile inherited */
- /**
- * Returns true if the file exists on disk.
- * @return boolean Whether file exist on disk.
- */
- public function exists() {
- $this->load();
- return $this->fileExists;
- }
- /** getTransformScript inherited */
- /** getUnscaledThumb inherited */
- /** thumbName inherited */
- /** createThumb inherited */
- /** transform inherited */
- /**
- * 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();
- /* Old code for bug 2532
- $thumbPath = "$thumbDir/$thumbName";
- if ( is_dir( $thumbPath ) ) {
- // Directory where file should be
- // This happened occasionally due to broken migration code in 1.5
- // Rename to broken-*
- for ( $i = 0; $i < 100 ; $i++ ) {
- $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
- if ( !file_exists( $broken ) ) {
- rename( $thumbPath, $broken );
- break;
- }
- }
- // Doesn't exist anymore
- clearstatcache();
- }
- */
- /*
- if ( $this->repo->fileExists( $thumbDir ) ) {
- // Delete file where directory should be
- $this->repo->cleanupBatch( array( $thumbDir ) );
- }
- */
- }
- /** getHandler inherited */
- /** iconThumb inherited */
- /** getLastError inherited */
- /**
- * Get all thumbnail names previously generated for this 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 ) {
- if ( $archiveName ) {
- $dir = $this->getArchiveThumbPath( $archiveName );
- } else {
- $dir = $this->getThumbPath();
- }
- $backend = $this->repo->getBackend();
- $files = array( $dir );
- $iterator = $backend->getFileList( array( 'dir' => $dir ) );
- foreach ( $iterator as $file ) {
- $files[] = $file;
- }
- return $files;
- }
- /**
- * Refresh metadata in memcached, but don't touch thumbnails or squid
- */
- function purgeMetadataCache() {
- $this->loadFromDB();
- $this->saveToCache();
- $this->purgeHistory();
- }
- /**
- * Purge the shared history (OldLocalFile) cache
- */
- function purgeHistory() {
- global $wgMemc;
- $hashedName = md5( $this->getName() );
- $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
- // Must purge thumbnails for old versions too! bug 30192
- foreach( $this->getHistory() as $oldFile ) {
- $oldFile->purgeThumbnails();
- }
- if ( $oldKey ) {
- $wgMemc->delete( $oldKey );
- }
- }
- /**
- * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
- */
- function purgeCache( $options = array() ) {
- // Refresh metadata cache
- $this->purgeMetadataCache();
- // Delete thumbnails
- $this->purgeThumbnails( $options );
- // Purge squid cache for this file
- SquidUpdate::purge( array( $this->getURL() ) );
- }
- /**
- * Delete cached transformed files for an archived version only.
- * @param $archiveName string name of the archived file
- */
- function purgeOldThumbnails( $archiveName ) {
- global $wgUseSquid;
- wfProfileIn( __METHOD__ );
- // Get a list of old thumbnails and URLs
- $files = $this->getThumbnails( $archiveName );
- $dir = array_shift( $files );
- $this->purgeThumbList( $dir, $files );
- // Purge any custom thumbnail caches
- wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
- // Purge the squid
- if ( $wgUseSquid ) {
- $urls = array();
- foreach( $files as $file ) {
- $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
- }
- SquidUpdate::purge( $urls );
- }
- wfProfileOut( __METHOD__ );
- }
- /**
- * Delete cached transformed files for the current version only.
- */
- function purgeThumbnails( $options = array() ) {
- global $wgUseSquid;
- wfProfileIn( __METHOD__ );
- // Delete thumbnails
- $files = $this->getThumbnails();
- // Give media handler a chance to filter the purge list
- if ( !empty( $options['forThumbRefresh'] ) ) {
- $handler = $this->getHandler();
- if ( $handler ) {
- $handler->filterThumbnailPurgeList( $files, $options );
- }
- }
- $dir = array_shift( $files );
- $this->purgeThumbList( $dir, $files );
- // Purge any custom thumbnail caches
- wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
- // Purge the squid
- if ( $wgUseSquid ) {
- $urls = array();
- foreach( $files as $file ) {
- $urls[] = $this->getThumbUrl( $file );
- }
- SquidUpdate::purge( $urls );
- }
- wfProfileOut( __METHOD__ );
- }
- /**
- * Delete a list of thumbnails visible at urls
- * @param $dir string base dir of the files.
- * @param $files array of strings: relative filenames (to $dir)
- */
- protected function purgeThumbList( $dir, $files ) {
- $fileListDebug = strtr(
- var_export( $files, true ),
- array("\n"=>'')
- );
- wfDebug( __METHOD__ . ": $fileListDebug\n" );
- $purgeList = array();
- foreach ( $files as $file ) {
- # Check that the base file name is part of the thumb name
- # This is a basic sanity check to avoid erasing unrelated directories
- if ( strpos( $file, $this->getName() ) !== false ) {
- $purgeList[] = "{$dir}/{$file}";
- }
- }
- # Delete the thumbnails
- $this->repo->quickPurgeBatch( $purgeList );
- # Clear out the thumbnail directory if empty
- $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' );
- $fields = OldLocalFile::selectFields();
- $conds = $opts = $join_conds = array();
- $eq = $inc ? '=' : '';
- $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
- if ( $start ) {
- $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
- }
- if ( $end ) {
- $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
- }
- if ( $limit ) {
- $opts['LIMIT'] = $limit;
- }
- // Search backwards for time > x queries
- $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
- $opts['ORDER BY'] = "oi_timestamp $order";
- $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
- wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
- &$conds, &$opts, &$join_conds ) );
- $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
- $r = array();
- foreach ( $res as $row ) {
- if ( $this->repo->oldFileFromRowFactory ) {
- $r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
- } else {
- $r[] = OldLocalFile::newFromRow( $row, $this->repo );
- }
- }
- if ( $order == 'ASC' ) {
- $r = array_reverse( $r ); // make sure it ends up descending
- }
- return $r;
- }
- /**
- * Return the history of this file, line by line.
- * starts with current version, then old versions.
- * uses $this->historyLine to check which line to return:
- * 0 return line for current version
- * 1 query for old versions, return first one
- * 2, ... return next old version from above query
- * @return bool
- */
- public function nextHistoryLine() {
- # Polymorphic function name to distinguish foreign and local fetches
- $fname = get_class( $this ) . '::' . __FUNCTION__;
- $dbr = $this->repo->getSlaveDB();
- if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
- $this->historyRes = $dbr->select( 'image',
- array(
- '*',
- "'' AS oi_archive_name",
- '0 as oi_deleted',
- 'img_sha1'
- ),
- array( 'img_name' => $this->title->getDBkey() ),
- $fname
- );
- if ( 0 == $dbr->numRows( $this->historyRes ) ) {
- $this->historyRes = null;
- return false;
- }
- } elseif ( $this->historyLine == 1 ) {
- $this->historyRes = $dbr->select( 'oldimage', '*',
- array( 'oi_name' => $this->title->getDBkey() ),
- $fname,
- array( 'ORDER BY' => 'oi_timestamp DESC' )
- );
- }
- $this->historyLine ++;
- return $dbr->fetchObject( $this->historyRes );
- }
- /**
- * Reset the history pointer to the first element of the history
- */
- public function resetHistory() {
- $this->historyLine = 0;
- if ( !is_null( $this->historyRes ) ) {
- $this->historyRes = null;
- }
- }
- /** getHashPath inherited */
- /** getRel inherited */
- /** getUrlRel inherited */
- /** getArchiveRel inherited */
- /** getArchivePath inherited */
- /** getThumbPath inherited */
- /** getArchiveUrl inherited */
- /** getThumbUrl inherited */
- /** getArchiveVirtualUrl inherited */
- /** getThumbVirtualUrl inherited */
- /** isHashed inherited */
- /**
- * Upload a file and record it in the DB
- * @param $srcPath String: source storage path or virtual URL
- * @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|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|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).
- $comment = $wgContLang->truncate( $comment, 255 );
- $this->lock(); // begin
- $status = $this->publish( $srcPath, $flags );
- if ( $status->successCount > 0 ) {
- # Essentially we are displacing any existing current file and saving
- # a new current file at the old location. If just the first succeeded,
- # we still need to displace the current DB entry and put in a new one.
- if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
- $status->fatal( 'filenotfound', $srcPath );
- }
- }
- $this->unlock(); // done
- return $status;
- }
- /**
- * 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 )
- {
- $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
- if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
- return false;
- }
- if ( $watch ) {
- global $wgUser;
- $wgUser->addWatch( $this->getTitle() );
- }
- return true;
- }
- /**
- * 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( __METHOD__ );
- if ( !$props ) {
- wfProfileIn( __METHOD__ . '-getProps' );
- $props = $this->repo->getFileProps( $this->getVirtualUrl() );
- wfProfileOut( __METHOD__ . '-getProps' );
- }
- if ( $timestamp === false ) {
- $timestamp = $dbw->timestamp();
- }
- $props['description'] = $comment;
- $props['user'] = $user->getId();
- $props['user_text'] = $user->getName();
- $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
- $this->setProps( $props );
- # Fail now if the file isn't there
- if ( !$this->fileExists ) {
- wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
- wfProfileOut( __METHOD__ );
- return false;
- }
- $reupload = false;
- # Test to see if the row exists using INSERT IGNORE
- # This avoids race conditions by locking the row until the commit, and also
- # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
- $dbw->insert( 'image',
- array(
- 'img_name' => $this->getName(),
- 'img_size' => $this->size,
- 'img_width' => intval( $this->width ),
- 'img_height' => intval( $this->height ),
- 'img_bits' => $this->bits,
- 'img_media_type' => $this->media_type,
- 'img_major_mime' => $this->major_mime,
- 'img_minor_mime' => $this->minor_mime,
- 'img_timestamp' => $timestamp,
- 'img_description' => $comment,
- 'img_user' => $user->getId(),
- 'img_user_text' => $user->getName(),
- 'img_metadata' => $this->metadata,
- 'img_sha1' => $this->sha1
- ),
- __METHOD__,
- 'IGNORE'
- );
- if ( $dbw->affectedRows() == 0 ) {
- # (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
- $dbw->insertSelect( 'oldimage', 'image',
- array(
- 'oi_name' => 'img_name',
- 'oi_archive_name' => $dbw->addQuotes( $oldver ),
- 'oi_size' => 'img_size',
- 'oi_width' => 'img_width',
- 'oi_height' => 'img_height',
- 'oi_bits' => 'img_bits',
- 'oi_timestamp' => 'img_timestamp',
- 'oi_description' => 'img_description',
- 'oi_user' => 'img_user',
- 'oi_user_text' => 'img_user_text',
- 'oi_metadata' => 'img_metadata',
- 'oi_media_type' => 'img_media_type',
- 'oi_major_mime' => 'img_major_mime',
- 'oi_minor_mime' => 'img_minor_mime',
- 'oi_sha1' => 'img_sha1'
- ),
- array( 'img_name' => $this->getName() ),
- __METHOD__
- );
- # Update the current image row
- $dbw->update( 'image',
- array( /* SET */
- 'img_size' => $this->size,
- 'img_width' => intval( $this->width ),
- 'img_height' => intval( $this->height ),
- 'img_bits' => $this->bits,
- 'img_media_type' => $this->media_type,
- 'img_major_mime' => $this->major_mime,
- 'img_minor_mime' => $this->minor_mime,
- 'img_timestamp' => $timestamp,
- 'img_description' => $comment,
- 'img_user' => $user->getId(),
- 'img_user_text' => $user->getName(),
- 'img_metadata' => $this->metadata,
- 'img_sha1' => $this->sha1
- ),
- array( 'img_name' => $this->getName() ),
- __METHOD__
- );
- } else {
- # This is a new file, so update the image count
- DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
- }
- $descTitle = $this->getTitle();
- $wikiPage = new WikiFilePage( $descTitle );
- $wikiPage->setFile( $this );
- # Add the log entry
- $log = new LogPage( 'upload' );
- $action = $reupload ? 'overwrite' : 'upload';
- $logId = $log->addEntry( $action, $descTitle, $comment, array(), $user );
- wfProfileIn( __METHOD__ . '-edit' );
- $exists = $descTitle->exists();
- if ( $exists ) {
- # Create a null revision
- $latest = $descTitle->getLatestRevID();
- $nullRevision = Revision::newNullRevision(
- $dbw,
- $descTitle->getArticleID(),
- $log->getRcComment(),
- false
- );
- if (!is_null($nullRevision)) {
- $nullRevision->insertOn( $dbw );
- 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();
- } else {
- # 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.
- $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
- }
- }
- wfProfileOut( __METHOD__ . '-edit' );
- # Save to cache and purge the squid
- # We shall not saveToCache before the commit since otherwise
- # in case of a rollback there is an usable file from memcached
- # 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' );
- $update->doUpdate();
- # Invalidate cache for all pages that redirects on this page
- $redirs = $this->getTitle()->getRedirectsHere();
- foreach ( $redirs as $redir ) {
- $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
- $update->doUpdate();
- }
- wfProfileOut( __METHOD__ );
- return true;
- }
- /**
- * Move or copy a file to its public location. If a file exists at the
- * destination, move it to an archive. Returns a FileRepoStatus object with
- * the archive name in the "value" member on success.
- *
- * The archive name should be passed through to recordUpload for database
- * registration.
- *
- * @param $srcPath String: local filesystem path to the source image
- * @param $flags Integer: a bitwise combination of:
- * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
- * @return FileRepoStatus object. On success, the value member contains the
- * archive name, or an empty string if it was a new file.
- */
- function publish( $srcPath, $flags = 0 ) {
- return $this->publishTo( $srcPath, $this->getRel(), $flags );
- }
- /**
- * Move or copy a file to a specified location. Returns a FileRepoStatus
- * object with the archive name in the "value" member on success.
- *
- * The archive name should be passed through to recordUpload for database
- * registration.
- *
- * @param $srcPath String: local filesystem path to the source image
- * @param $dstRel String: target relative path
- * @param $flags Integer: a bitwise combination of:
- * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
- * @return FileRepoStatus object. On success, the value member contains the
- * 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();
- $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
- $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
- $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
- if ( $status->value == 'new' ) {
- $status->value = '';
- } else {
- $status->value = $archiveName;
- }
- $this->unlock(); // done
- return $status;
- }
- /** getLinksTo inherited */
- /** getExifData inherited */
- /** isLocal inherited */
- /** wasDeleted inherited */
- /**
- * Move file to the new title
- *
- * Move current, old version and all thumbnails
- * to the new filename. Old file is deleted.
- *
- * Cache purging is done; checks for validity
- * and logging are caller's responsibility
- *
- * @param $target Title New file name
- * @return FileRepoStatus object.
- */
- function move( $target ) {
- if ( $this->getRepo()->getReadOnlyReason() !== false ) {
- return $this->readOnlyFatalStatus();
- }
- wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
- $batch = new LocalFileMoveBatch( $this, $target );
- $this->lock(); // begin
- $batch->addCurrent();
- $archiveNames = $batch->addOlds();
- $status = $batch->execute();
- $this->unlock(); // done
- wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
- $this->purgeEverything();
- foreach ( $archiveNames as $archiveName ) {
- $this->purgeOldThumbnails( $archiveName );
- }
- if ( $status->isOK() ) {
- // Now switch the object
- $this->title = $target;
- // Force regeneration of the name and hashpath
- unset( $this->name );
- unset( $this->hashPath );
- // Purge the new image
- $this->purgeEverything();
- }
- return $status;
- }
- /**
- * Delete all versions of the file.
- *
- * Moves the files into an archive directory (or deletes them)
- * and removes the database rows.
- *
- * Cache purging is done; logging is caller's responsibility.
- *
- * @param $reason
- * @param $suppress
- * @return FileRepoStatus object.
- */
- function delete( $reason, $suppress = false ) {
- if ( $this->getRepo()->getReadOnlyReason() !== false ) {
- return $this->readOnlyFatalStatus();
- }
- $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
- $this->lock(); // begin
- $batch->addCurrent();
- # Get old version relative paths
- $archiveNames = $batch->addOlds();
- $status = $batch->execute();
- $this->unlock(); // done
- if ( $status->isOK() ) {
- DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
- }
- $this->purgeEverything();
- foreach ( $archiveNames as $archiveName ) {
- $this->purgeOldThumbnails( $archiveName );
- }
- return $status;
- }
- /**
- * Delete an old version of the file.
- *
- * Moves the file into an archive directory (or deletes it)
- * and removes the database row.
- *
- * Cache purging is done; logging is caller's responsibility.
- *
- * @param $archiveName String
- * @param $reason String
- * @param $suppress Boolean
- * @throws MWException or FSException on database or file store failure
- * @return FileRepoStatus object.
- */
- function deleteOld( $archiveName, $reason, $suppress = false ) {
- if ( $this->getRepo()->getReadOnlyReason() !== false ) {
- return $this->readOnlyFatalStatus();
- }
- $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
- $this->lock(); // begin
- $batch->addOld( $archiveName );
- $status = $batch->execute();
- $this->unlock(); // done
- $this->purgeOldThumbnails( $archiveName );
- if ( $status->isOK() ) {
- $this->purgeDescription();
- $this->purgeHistory();
- }
- return $status;
- }
- /**
- * Restore all or specified deleted revisions to the given file.
- * Permissions and logging are left to the caller.
- *
- * May throw database exceptions on error.
- *
- * @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() ) {
- $cleanupStatus = $batch->cleanup();
- $cleanupStatus->successCount = 0;
- $cleanupStatus->failCount = 0;
- $status->merge( $cleanupStatus );
- }
- $this->unlock(); // done
- return $status;
- }
- /** isMultipage inherited */
- /** pageCount inherited */
- /** scaleHeight inherited */
- /** getImageSize inherited */
- /**
- * Get the URL of the file description page.
- * @return String
- */
- function getDescriptionUrl() {
- return $this->title->getLocalUrl();
- }
- /**
- * 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, false, Revision::READ_NORMAL );
- if ( !$revision ) return false;
- $text = $revision->getText();
- if ( !$text ) return false;
- $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
- return $pout->getText();
- }
- /**
- * @return string
- */
- function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
- $this->load();
- 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
- if ( $this->sha1 == '' && $this->fileExists ) {
- $this->lock(); // begin
- $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
- if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
- $dbw = $this->repo->getMasterDB();
- $dbw->update( 'image',
- array( 'img_sha1' => $this->sha1 ),
- array( 'img_name' => $this->getName() ),
- __METHOD__ );
- $this->saveToCache();
- }
- $this->unlock(); // done
- }
- return $this->sha1;
- }
- /**
- * @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
- */
- function lock() {
- $dbw = $this->repo->getMasterDB();
- if ( !$this->locked ) {
- $dbw->begin( __METHOD__ );
- $this->locked++;
- }
- return $dbw->selectField( 'image', '1',
- array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
- }
- /**
- * Decrement the lock reference count. If the reference count is reduced to zero, commits
- * the transaction and thereby releases the image lock.
- */
- function unlock() {
- if ( $this->locked ) {
- --$this->locked;
- if ( !$this->locked ) {
- $dbw = $this->repo->getMasterDB();
- $dbw->commit( __METHOD__ );
- }
- }
- }
- /**
- * Roll back the DB transaction and mark the image unlocked
- */
- function unlockAndRollback() {
- $this->locked = false;
- $dbw = $this->repo->getMasterDB();
- $dbw->rollback( __METHOD__ );
- }
- /**
- * @return Status
- */
- protected function readOnlyFatalStatus() {
- return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
- $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
- }
- } // LocalFile class
- # ------------------------------------------------------------------------------
- /**
- * Helper class for file deletion
- * @ingroup FileAbstraction
- */
- class LocalFileDeleteBatch {
- /**
- * @var LocalFile
- */
- var $file;
- 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;
- $this->suppress = $suppress;
- $this->status = $file->repo->newGood();
- }
- function addCurrent() {
- $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;
- $deleteCurrent = false;
- } else {
- $oldRels = $this->srcRels;
- unset( $oldRels['.'] );
- $deleteCurrent = true;
- }
- return array( $oldRels, $deleteCurrent );
- }
- /**
- * @return array
- */
- protected function getHashes() {
- $hashes = array();
- list( $oldRels, $deleteCurrent ) = $this->getOldRels();
- if ( $deleteCurrent ) {
- $hashes['.'] = $this->file->getSha1();
- }
- if ( count( $oldRels ) ) {
- $dbw = $this->file->repo->getMasterDB();
- $res = $dbw->select(
- 'oldimage',
- array( 'oi_archive_name', 'oi_sha1' ),
- 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
- __METHOD__
- );
- foreach ( $res as $row ) {
- if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
- // Get the hash from the file
- $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
- $props = $this->file->repo->getFileProps( $oldUrl );
- if ( $props['fileExists'] ) {
- // Upgrade the oldimage row
- $dbw->update( 'oldimage',
- array( 'oi_sha1' => $props['sha1'] ),
- array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
- __METHOD__ );
- $hashes[$row->oi_archive_name] = $props['sha1'];
- } else {
- $hashes[$row->oi_archive_name] = false;
- }
- } else {
- $hashes[$row->oi_archive_name] = $row->oi_sha1;
- }
- }
- }
- $missing = array_diff_key( $this->srcRels, $hashes );
- foreach ( $missing as $name => $rel ) {
- $this->status->error( 'filedelete-old-unregistered', $name );
- }
- foreach ( $hashes as $name => $hash ) {
- if ( !$hash ) {
- $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
- unset( $hashes[$name] );
- }
- }
- return $hashes;
- }
- function doDBInserts() {
- global $wgUser;
- $dbw = $this->file->repo->getMasterDB();
- $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
- $encUserId = $dbw->addQuotes( $wgUser->getId() );
- $encReason = $dbw->addQuotes( $this->reason );
- $encGroup = $dbw->addQuotes( 'deleted' );
- $ext = $this->file->getExtension();
- $dotExt = $ext === '' ? '' : ".$ext";
- $encExt = $dbw->addQuotes( $dotExt );
- list( $oldRels, $deleteCurrent ) = $this->getOldRels();
- // Bitfields to further suppress the content
- if ( $this->suppress ) {
- $bitfield = 0;
- // This should be 15...
- $bitfield |= Revision::DELETED_TEXT;
- $bitfield |= Revision::DELETED_COMMENT;
- $bitfield |= Revision::DELETED_USER;
- $bitfield |= Revision::DELETED_RESTRICTED;
- } else {
- $bitfield = 'oi_deleted';
- }
- if ( $deleteCurrent ) {
- $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
- $where = array( 'img_name' => $this->file->getName() );
- $dbw->insertSelect( 'filearchive', 'image',
- array(
- 'fa_storage_group' => $encGroup,
- 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
- 'fa_deleted_user' => $encUserId,
- 'fa_deleted_timestamp' => $encTimestamp,
- 'fa_deleted_reason' => $encReason,
- 'fa_deleted' => $this->suppress ? $bitfield : 0,
- 'fa_name' => 'img_name',
- 'fa_archive_name' => 'NULL',
- 'fa_size' => 'img_size',
- 'fa_width' => 'img_width',
- 'fa_height' => 'img_height',
- 'fa_metadata' => 'img_metadata',
- 'fa_bits' => 'img_bits',
- 'fa_media_type' => 'img_media_type',
- 'fa_major_mime' => 'img_major_mime',
- 'fa_minor_mime' => 'img_minor_mime',
- 'fa_description' => 'img_description',
- 'fa_user' => 'img_user',
- 'fa_user_text' => 'img_user_text',
- 'fa_timestamp' => 'img_timestamp'
- ), $where, __METHOD__ );
- }
- if ( count( $oldRels ) ) {
- $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
- $where = array(
- 'oi_name' => $this->file->getName(),
- 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
- $dbw->insertSelect( 'filearchive', 'oldimage',
- array(
- 'fa_storage_group' => $encGroup,
- 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
- 'fa_deleted_user' => $encUserId,
- 'fa_deleted_timestamp' => $encTimestamp,
- 'fa_deleted_reason' => $encReason,
- 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
- 'fa_name' => 'oi_name',
- 'fa_archive_name' => 'oi_archive_name',
- 'fa_size' => 'oi_size',
- 'fa_width' => 'oi_width',
- 'fa_height' => 'oi_height',
- 'fa_metadata' => 'oi_metadata',
- 'fa_bits' => 'oi_bits',
- 'fa_media_type' => 'oi_media_type',
- 'fa_major_mime' => 'oi_major_mime',
- 'fa_minor_mime' => 'oi_minor_mime',
- 'fa_description' => 'oi_description',
- 'fa_user' => 'oi_user',
- 'fa_user_text' => 'oi_user_text',
- 'fa_timestamp' => 'oi_timestamp',
- ), $where, __METHOD__ );
- }
- }
- function doDBDeletes() {
- $dbw = $this->file->repo->getMasterDB();
- list( $oldRels, $deleteCurrent ) = $this->getOldRels();
- if ( count( $oldRels ) ) {
- $dbw->delete( 'oldimage',
- array(
- 'oi_name' => $this->file->getName(),
- 'oi_archive_name' => array_keys( $oldRels )
- ), __METHOD__ );
- }
- if ( $deleteCurrent ) {
- $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
- }
- }
- /**
- * Run the transaction
- * @return FileRepoStatus
- */
- function execute() {
- wfProfileIn( __METHOD__ );
- $this->file->lock();
- // Leave private files alone
- $privateFiles = array();
- list( $oldRels, $deleteCurrent ) = $this->getOldRels();
- $dbw = $this->file->repo->getMasterDB();
- if ( !empty( $oldRels ) ) {
- $res =…
Large files files are truncated, but you can click here to view the full file