3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\FileRepo\File\FileSelectQueryBuilder
;
22 use MediaWiki\MediaWikiServices
;
23 use MediaWiki\Permissions\Authority
;
24 use MediaWiki\Revision\RevisionRecord
;
25 use MediaWiki\Status\Status
;
26 use MediaWiki\Title\Title
;
27 use MediaWiki\User\UserIdentity
;
28 use Wikimedia\Rdbms\IDBAccessObject
;
29 use Wikimedia\Rdbms\IReadableDatabase
;
30 use Wikimedia\Rdbms\SelectQueryBuilder
;
33 * Old file in the oldimage table.
36 * @ingroup FileAbstraction
38 class OldLocalFile
extends LocalFile
{
39 /** @var string|int Timestamp */
40 protected $requestedTime;
42 /** @var string|null Archive name */
43 protected $archive_name;
45 public const CACHE_VERSION
= 1;
50 * @param LocalRepo $repo
51 * @param string|int|null $time
54 public static function newFromTitle( $title, $repo, $time = null ) {
55 # The null default value is only here to avoid an E_STRICT
56 if ( $time === null ) {
57 throw new InvalidArgumentException( __METHOD__
. ' got null for $time parameter' );
60 return new static( $title, $repo, $time, null );
67 * @param LocalRepo $repo
68 * @param string $archiveName
71 public static function newFromArchiveName( $title, $repo, $archiveName ) {
72 return new static( $title, $repo, null, $archiveName );
78 * @param stdClass $row
79 * @param LocalRepo $repo
82 public static function newFromRow( $row, $repo ) {
83 $title = Title
::makeTitle( NS_FILE
, $row->oi_name
);
84 $file = new static( $title, $repo, null, $row->oi_archive_name
);
85 $file->loadFromRow( $row, 'oi_' );
91 * Create a OldLocalFile from a SHA-1 key
92 * Do not call this except from inside a repo class.
96 * @param string $sha1 Base-36 SHA-1
97 * @param LocalRepo $repo
98 * @param string|false $timestamp MW_timestamp (optional)
100 * @return static|false
102 public static function newFromKey( $sha1, $repo, $timestamp = false ) {
103 $dbr = $repo->getReplicaDB();
104 $queryBuilder = FileSelectQueryBuilder
::newForOldFile( $dbr );
106 $queryBuilder->where( [ 'oi_sha1' => $sha1 ] );
108 $queryBuilder->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $timestamp ) ] );
111 $row = $queryBuilder->caller( __METHOD__
)->fetchRow();
113 return static::newFromRow( $row, $repo );
120 * Return the tables, fields, and join conditions to be selected to create
121 * a new oldlocalfile object.
123 * Since 1.34, oi_user and oi_user_text have not been present in the
124 * database, but they continue to be available in query results as
128 * @stable to override
130 * @deprecated since 1.41 use FileSelectQueryBuilder instead
131 * @param string[] $options
132 * - omit-lazy: Omit fields that are lazily cached.
133 * @return array[] With three keys:
134 * - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
135 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
136 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
137 * @phan-return array{tables:string[],fields:string[],joins:array}
139 public static function getQueryInfo( array $options = [] ) {
140 $dbr = MediaWikiServices
::getInstance()->getConnectionProvider()->getReplicaDatabase();
141 $queryInfo = FileSelectQueryBuilder
::newForOldFile( $dbr, $options )->getQueryInfo();
143 'tables' => $queryInfo['tables'],
144 'fields' => $queryInfo['fields'],
145 'joins' => $queryInfo['join_conds'],
152 * @param Title $title
153 * @param LocalRepo $repo
154 * @param string|int|null $time Timestamp or null to load by archive name
155 * @param string|null $archiveName Archive name or null to load by timestamp
157 public function __construct( $title, $repo, $time, $archiveName ) {
158 parent
::__construct( $title, $repo );
159 $this->requestedTime
= $time;
160 $this->archive_name
= $archiveName;
161 if ( $time === null && $archiveName === null ) {
162 throw new LogicException( __METHOD__
. ': must specify at least one of $time or $archiveName' );
166 public function loadFromRow( $row, $prefix = 'img_' ) {
167 $this->archive_name
= $row->{"{$prefix}archive_name"};
168 $this->deleted
= $row->{"{$prefix}deleted"};
170 unset( $row->{"{$prefix}archive_name"} );
171 unset( $row->{"{$prefix}deleted"} );
172 parent
::loadFromRow( $row, $prefix );
176 * @stable to override
179 protected function getCacheKey() {
184 * @stable to override
187 public function getArchiveName() {
188 if ( $this->archive_name
=== null ) {
192 return $this->archive_name
;
198 public function isOld() {
205 public function isVisible() {
206 return $this->exists() && !$this->isDeleted( File
::DELETED_FILE
);
210 * @stable to override
213 protected function loadFromDB( $flags = 0 ) {
214 $this->dataLoaded
= true;
216 $dbr = ( $flags & IDBAccessObject
::READ_LATEST
)
217 ?
$this->repo
->getPrimaryDB()
218 : $this->repo
->getReplicaDB();
219 $queryBuilder = $this->buildQueryBuilderForLoad( $dbr, [] );
220 $row = $queryBuilder->caller( __METHOD__
)->fetchRow();
222 $this->loadFromRow( $row, 'oi_' );
224 $this->fileExists
= false;
229 * Load lazy file metadata from the DB
230 * @stable to override
232 protected function loadExtraFromDB() {
233 $this->extraDataLoaded
= true;
234 $dbr = $this->repo
->getReplicaDB();
235 $queryBuilder = $this->buildQueryBuilderForLoad( $dbr );
237 // In theory the file could have just been renamed/deleted...oh well
238 $row = $queryBuilder->caller( __METHOD__
)->fetchRow();
240 if ( !$row ) { // fallback to primary DB
241 $dbr = $this->repo
->getPrimaryDB();
242 $queryBuilder = $this->buildQueryBuilderForLoad( $dbr );
243 $row = $queryBuilder->caller( __METHOD__
)->fetchRow();
247 foreach ( $this->unprefixRow( $row, 'oi_' ) as $name => $value ) {
248 $this->$name = $value;
251 throw new RuntimeException( "Could not find data for image '{$this->archive_name}'." );
255 private function buildQueryBuilderForLoad( IReadableDatabase
$dbr, $options = [ 'omit-nonlazy' ] ) {
256 $queryBuilder = FileSelectQueryBuilder
::newForOldFile( $dbr, $options );
257 $queryBuilder->where( [ 'oi_name' => $this->getName() ] )
258 ->orderBy( 'oi_timestamp', SelectQueryBuilder
::SORT_DESC
);
259 if ( $this->requestedTime
=== null ) {
260 $queryBuilder->andWhere( [ 'oi_archive_name' => $this->archive_name
] );
262 $queryBuilder->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $this->requestedTime
) ] );
264 return $queryBuilder;
269 * @stable to override
271 protected function getCacheFields( $prefix = 'img_' ) {
272 $fields = parent
::getCacheFields( $prefix );
273 $fields[] = $prefix . 'archive_name';
274 $fields[] = $prefix . 'deleted';
281 * @stable to override
283 public function getRel() {
284 return $this->getArchiveRel( $this->getArchiveName() );
289 * @stable to override
291 public function getUrlRel() {
292 return $this->getArchiveRel( rawurlencode( $this->getArchiveName() ) );
296 * @stable to override
298 public function upgradeRow() {
299 $this->loadFromFile();
301 # Don't destroy file info of missing files
302 if ( !$this->fileExists
) {
303 wfDebug( __METHOD__
. ": file does not exist, aborting" );
308 $dbw = $this->repo
->getPrimaryDB();
309 [ $major, $minor ] = self
::splitMime( $this->mime
);
311 wfDebug( __METHOD__
. ': upgrading ' . $this->archive_name
. " to the current schema" );
312 $dbw->newUpdateQueryBuilder()
313 ->update( 'oldimage' )
315 'oi_size' => $this->size
,
316 'oi_width' => $this->width
,
317 'oi_height' => $this->height
,
318 'oi_bits' => $this->bits
,
319 'oi_media_type' => $this->media_type
,
320 'oi_major_mime' => $major,
321 'oi_minor_mime' => $minor,
322 'oi_metadata' => $this->getMetadataForDb( $dbw ),
323 'oi_sha1' => $this->sha1
,
326 'oi_name' => $this->getName(),
327 'oi_archive_name' => $this->archive_name
,
329 ->caller( __METHOD__
)->execute();
332 protected function reserializeMetadata() {
333 // TODO: implement this and make it possible to hit it from refreshImageMetadata.php
334 // It can be hit from action=purge but that's not very useful if the
335 // goal is to reserialize the whole oldimage table.
339 * @param int $field One of DELETED_* bitfield constants for file or
343 public function isDeleted( $field ) {
346 return ( $this->deleted
& $field ) == $field;
350 * Returns bitfield value
353 public function getVisibility() {
356 return (int)$this->deleted
;
360 * Determine if the current user is allowed to view a particular
361 * field of this image file, if it's marked as deleted.
364 * @param Authority $performer User object to check
367 public function userCan( $field, Authority
$performer ) {
370 return RevisionRecord
::userCanBitfield(
378 * Upload a file directly into archive. Generally for Special:Import.
380 * @param string $srcPath File system path of the source file
381 * @param string $timestamp
382 * @param string $comment
383 * @param UserIdentity $user
386 public function uploadOld( $srcPath, $timestamp, $comment, UserIdentity
$user ) {
387 $archiveName = $this->getArchiveName();
388 $dstRel = $this->getArchiveRel( $archiveName );
389 $status = $this->publishTo( $srcPath, $dstRel );
391 if ( $status->isGood() &&
392 !$this->recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user )
394 $status->fatal( 'filenotfound', $srcPath );
401 * Record a file upload in the oldimage table, without adding log entries.
402 * @stable to override
404 * @param string $srcPath File system path to the source file
405 * @param string $archiveName The archive name of the file
406 * @param string $timestamp
407 * @param string $comment Upload comment
408 * @param UserIdentity $user User who did this upload
411 protected function recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user ) {
412 $dbw = $this->repo
->getPrimaryDB();
414 $services = MediaWikiServices
::getInstance();
415 $mwProps = new MWFileProps( $services->getMimeAnalyzer() );
416 $props = $mwProps->getPropsFromPath( $srcPath, true );
417 if ( !$props['fileExists'] ) {
420 $this->setProps( $props );
422 $dbw->startAtomic( __METHOD__
);
423 $commentFields = $services->getCommentStore()
424 ->insert( $dbw, 'oi_description', $comment );
425 $actorId = $services->getActorNormalization()
426 ->acquireActorId( $user, $dbw );
427 $dbw->newInsertQueryBuilder()
428 ->insertInto( 'oldimage' )
430 'oi_name' => $this->getName(),
431 'oi_archive_name' => $archiveName,
432 'oi_size' => $props['size'],
433 'oi_width' => intval( $props['width'] ),
434 'oi_height' => intval( $props['height'] ),
435 'oi_bits' => $props['bits'],
436 'oi_actor' => $actorId,
437 'oi_timestamp' => $dbw->timestamp( $timestamp ),
438 'oi_metadata' => $this->getMetadataForDb( $dbw ),
439 'oi_media_type' => $props['media_type'],
440 'oi_major_mime' => $props['major_mime'],
441 'oi_minor_mime' => $props['minor_mime'],
442 'oi_sha1' => $props['sha1'],
444 ->caller( __METHOD__
)->execute();
445 $dbw->endAtomic( __METHOD__
);
451 * If archive name is an empty string, then file does not "exist"
453 * This is the case for a couple files on Wikimedia servers where
454 * the old version is "lost".
457 public function exists() {
458 $archiveName = $this->getArchiveName();
459 if ( $archiveName === '' ||
!is_string( $archiveName ) ) {
462 return parent
::exists();