Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 198
0.00% covered (danger)
0.00%
0 / 25
CRAP
0.00% covered (danger)
0.00%
0 / 1
OldLocalFile
0.00% covered (danger)
0.00%
0 / 197
0.00% covered (danger)
0.00%
0 / 25
2162
0.00% covered (danger)
0.00%
0 / 1
 newFromTitle
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 newFromArchiveName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 newFromRow
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 newFromKey
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 getQueryInfo
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 __construct
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 loadFromRow
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 getCacheKey
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getArchiveName
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 isOld
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isVisible
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 loadFromDB
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 loadExtraFromDB
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 buildQueryBuilderForLoad
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getCacheFields
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getRel
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getUrlRel
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 upgradeRow
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
12
 reserializeMetadata
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isDeleted
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getVisibility
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 userCan
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 uploadOld
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 recordOldUpload
0.00% covered (danger)
0.00%
0 / 54
0.00% covered (danger)
0.00%
0 / 1
12
 exists
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21namespace MediaWiki\FileRepo\File;
22
23use InvalidArgumentException;
24use LogicException;
25use MediaWiki\FileRepo\LocalRepo;
26use MediaWiki\MainConfigNames;
27use MediaWiki\MediaWikiServices;
28use MediaWiki\Permissions\Authority;
29use MediaWiki\Revision\RevisionRecord;
30use MediaWiki\Status\Status;
31use MediaWiki\Title\Title;
32use MediaWiki\User\UserIdentity;
33use MWFileProps;
34use RuntimeException;
35use stdClass;
36use Wikimedia\Rdbms\IDBAccessObject;
37use Wikimedia\Rdbms\IReadableDatabase;
38use Wikimedia\Rdbms\SelectQueryBuilder;
39
40/**
41 * Old file in the oldimage table.
42 *
43 * @stable to extend
44 * @ingroup FileAbstraction
45 */
46class OldLocalFile extends LocalFile {
47    /** @var string|int Timestamp */
48    protected $requestedTime;
49
50    /** @var string|null Archive name */
51    protected $archive_name;
52
53    public const CACHE_VERSION = 1;
54
55    /**
56     * @stable to override
57     * @param Title $title
58     * @param LocalRepo $repo
59     * @param string|int|null $time
60     * @return static
61     */
62    public static function newFromTitle( $title, $repo, $time = null ) {
63        # The null default value is only here to avoid an E_STRICT
64        if ( $time === null ) {
65            throw new InvalidArgumentException( __METHOD__ . ' got null for $time parameter' );
66        }
67
68        return new static( $title, $repo, $time, null );
69    }
70
71    /**
72     * @stable to override
73     *
74     * @param Title $title
75     * @param LocalRepo $repo
76     * @param string $archiveName
77     * @return static
78     */
79    public static function newFromArchiveName( $title, $repo, $archiveName ) {
80        return new static( $title, $repo, null, $archiveName );
81    }
82
83    /**
84     * @stable to override
85     *
86     * @param stdClass $row
87     * @param LocalRepo $repo
88     * @return static
89     */
90    public static function newFromRow( $row, $repo ) {
91        $title = Title::makeTitle( NS_FILE, $row->oi_name );
92        $file = new static( $title, $repo, null, $row->oi_archive_name );
93        $file->loadFromRow( $row, 'oi_' );
94
95        return $file;
96    }
97
98    /**
99     * Create a OldLocalFile from a SHA-1 key
100     * Do not call this except from inside a repo class.
101     *
102     * @stable to override
103     *
104     * @param string $sha1 Base-36 SHA-1
105     * @param LocalRepo $repo
106     * @param string|false $timestamp MW_timestamp (optional)
107     *
108     * @return static|false
109     */
110    public static function newFromKey( $sha1, $repo, $timestamp = false ) {
111        $dbr = $repo->getReplicaDB();
112        $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr );
113
114        $queryBuilder->where( [ 'oi_sha1' => $sha1 ] );
115        if ( $timestamp ) {
116            $queryBuilder->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $timestamp ) ] );
117        }
118
119        $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
120        if ( $row ) {
121            return static::newFromRow( $row, $repo );
122        } else {
123            return false;
124        }
125    }
126
127    /**
128     * Return the tables, fields, and join conditions to be selected to create
129     * a new oldlocalfile object.
130     *
131     * Since 1.34, oi_user and oi_user_text have not been present in the
132     * database, but they continue to be available in query results as
133     * aliases.
134     *
135     * @since 1.31
136     * @stable to override
137     *
138     * @deprecated since 1.41 use FileSelectQueryBuilder instead
139     * @param string[] $options
140     *   - omit-lazy: Omit fields that are lazily cached.
141     * @return array[] With three keys:
142     *   - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
143     *   - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
144     *   - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
145     * @phan-return array{tables:string[],fields:string[],joins:array}
146     */
147    public static function getQueryInfo( array $options = [] ) {
148        wfDeprecated( __METHOD__, '1.41' );
149        $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
150        $queryInfo = FileSelectQueryBuilder::newForOldFile( $dbr, $options )->getQueryInfo();
151        return [
152            'tables' => $queryInfo['tables'],
153            'fields' => $queryInfo['fields'],
154            'joins' => $queryInfo['join_conds'],
155        ];
156    }
157
158    /**
159     * @stable to call
160     *
161     * @param Title $title
162     * @param LocalRepo $repo
163     * @param string|int|null $time Timestamp or null to load by archive name
164     * @param string|null $archiveName Archive name or null to load by timestamp
165     */
166    public function __construct( $title, $repo, $time, $archiveName ) {
167        parent::__construct( $title, $repo );
168        $this->requestedTime = $time;
169        $this->archive_name = $archiveName;
170        if ( $time === null && $archiveName === null ) {
171            throw new LogicException( __METHOD__ . ': must specify at least one of $time or $archiveName' );
172        }
173    }
174
175    public function loadFromRow( $row, $prefix = 'img_' ) {
176        $this->archive_name = $row->{"{$prefix}archive_name"};
177        $this->deleted = $row->{"{$prefix}deleted"};
178        $row = clone $row;
179        unset( $row->{"{$prefix}archive_name"} );
180        unset( $row->{"{$prefix}deleted"} );
181        parent::loadFromRow( $row, $prefix );
182    }
183
184    /**
185     * @stable to override
186     * @return bool
187     */
188    protected function getCacheKey() {
189        return false;
190    }
191
192    /**
193     * @stable to override
194     * @return string
195     */
196    public function getArchiveName() {
197        if ( $this->archive_name === null ) {
198            $this->load();
199        }
200
201        return $this->archive_name;
202    }
203
204    /**
205     * @return bool
206     */
207    public function isOld() {
208        return true;
209    }
210
211    /**
212     * @return bool
213     */
214    public function isVisible() {
215        return $this->exists() && !$this->isDeleted( File::DELETED_FILE );
216    }
217
218    /**
219     * @stable to override
220     * @param int $flags
221     */
222    protected function loadFromDB( $flags = 0 ) {
223        $this->dataLoaded = true;
224
225        $dbr = ( $flags & IDBAccessObject::READ_LATEST )
226            ? $this->repo->getPrimaryDB()
227            : $this->repo->getReplicaDB();
228        $queryBuilder = $this->buildQueryBuilderForLoad( $dbr, [] );
229        $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
230        if ( $row ) {
231            $this->loadFromRow( $row, 'oi_' );
232        } else {
233            $this->fileExists = false;
234        }
235    }
236
237    /**
238     * Load lazy file metadata from the DB
239     * @stable to override
240     */
241    protected function loadExtraFromDB() {
242        $this->extraDataLoaded = true;
243        $dbr = $this->repo->getReplicaDB();
244        $queryBuilder = $this->buildQueryBuilderForLoad( $dbr );
245
246        // In theory the file could have just been renamed/deleted...oh well
247        $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
248
249        if ( !$row ) { // fallback to primary DB
250            $dbr = $this->repo->getPrimaryDB();
251            $queryBuilder = $this->buildQueryBuilderForLoad( $dbr );
252            $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
253        }
254
255        if ( $row ) {
256            foreach ( $this->unprefixRow( $row, 'oi_' ) as $name => $value ) {
257                $this->$name = $value;
258            }
259        } else {
260            throw new RuntimeException( "Could not find data for image '{$this->archive_name}'." );
261        }
262    }
263
264    private function buildQueryBuilderForLoad(
265        IReadableDatabase $dbr, array $options = [ 'omit-nonlazy' ]
266    ): FileSelectQueryBuilder {
267        $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr, $options );
268        $queryBuilder->where( [ 'oi_name' => $this->getName() ] )
269            ->orderBy( 'oi_timestamp', SelectQueryBuilder::SORT_DESC );
270        if ( $this->requestedTime === null ) {
271            $queryBuilder->andWhere( [ 'oi_archive_name' => $this->archive_name ] );
272        } else {
273            $queryBuilder->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $this->requestedTime ) ] );
274        }
275        return $queryBuilder;
276    }
277
278    /**
279     * @inheritDoc
280     * @stable to override
281     */
282    protected function getCacheFields( $prefix = 'img_' ) {
283        $fields = parent::getCacheFields( $prefix );
284        $fields[] = $prefix . 'archive_name';
285        $fields[] = $prefix . 'deleted';
286
287        return $fields;
288    }
289
290    /**
291     * @return string
292     * @stable to override
293     */
294    public function getRel() {
295        return $this->getArchiveRel( $this->getArchiveName() );
296    }
297
298    /**
299     * @return string
300     * @stable to override
301     */
302    public function getUrlRel() {
303        return $this->getArchiveRel( rawurlencode( $this->getArchiveName() ) );
304    }
305
306    /**
307     * @stable to override
308     */
309    public function upgradeRow() {
310        $this->loadFromFile();
311
312        # Don't destroy file info of missing files
313        if ( !$this->fileExists ) {
314            wfDebug( __METHOD__ . ": file does not exist, aborting" );
315
316            return;
317        }
318
319        $dbw = $this->repo->getPrimaryDB();
320        [ $major, $minor ] = self::splitMime( $this->mime );
321        $metadata = $this->getMetadataForDb( $dbw );
322
323        wfDebug( __METHOD__ . ': upgrading ' . $this->archive_name . " to the current schema" );
324        $dbw->newUpdateQueryBuilder()
325            ->update( 'oldimage' )
326            ->set( [
327                'oi_size' => $this->size,
328                'oi_width' => $this->width,
329                'oi_height' => $this->height,
330                'oi_bits' => $this->bits,
331                'oi_media_type' => $this->media_type,
332                'oi_major_mime' => $major,
333                'oi_minor_mime' => $minor,
334                'oi_metadata' => $metadata,
335                'oi_sha1' => $this->sha1,
336            ] )
337            ->where( [
338                'oi_name' => $this->getName(),
339                'oi_archive_name' => $this->archive_name,
340            ] )
341            ->caller( __METHOD__ )->execute();
342
343        $migrationStage = MediaWikiServices::getInstance()->getMainConfig()->get(
344            MainConfigNames::FileSchemaMigrationStage
345        );
346        if ( $migrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
347            $dbw->newUpdateQueryBuilder()
348                ->update( 'filerevision' )
349                ->set( [
350                    'fr_size' => $this->size,
351                    'fr_width' => $this->width,
352                    'fr_height' => $this->height,
353                    'fr_bits' => $this->bits,
354                    'fr_metadata' => $metadata,
355                    'fr_sha1' => $this->sha1,
356                ] )
357                ->where( [
358                    'fr_file' => $this->acquireFileIdFromName(),
359                    'fr_archive_name' => $this->archive_name,
360                ] )
361                ->caller( __METHOD__ )->execute();
362        }
363    }
364
365    protected function reserializeMetadata() {
366        // TODO: implement this and make it possible to hit it from refreshImageMetadata.php
367        // It can be hit from action=purge but that's not very useful if the
368        // goal is to reserialize the whole oldimage table.
369    }
370
371    /**
372     * @param int $field One of DELETED_* bitfield constants for file or
373     *   revision rows
374     * @return bool
375     */
376    public function isDeleted( $field ) {
377        $this->load();
378
379        return ( $this->deleted & $field ) == $field;
380    }
381
382    /**
383     * Returns bitfield value
384     * @return int
385     */
386    public function getVisibility() {
387        $this->load();
388
389        return (int)$this->deleted;
390    }
391
392    /**
393     * Determine if the current user is allowed to view a particular
394     * field of this image file, if it's marked as deleted.
395     *
396     * @param int $field
397     * @param Authority $performer User object to check
398     * @return bool
399     */
400    public function userCan( $field, Authority $performer ) {
401        $this->load();
402
403        return RevisionRecord::userCanBitfield(
404            $this->deleted,
405            $field,
406            $performer
407        );
408    }
409
410    /**
411     * Upload a file directly into archive. Generally for Special:Import.
412     *
413     * @param string $srcPath File system path of the source file
414     * @param string $timestamp
415     * @param string $comment
416     * @param UserIdentity $user
417     * @return Status
418     */
419    public function uploadOld( $srcPath, $timestamp, $comment, UserIdentity $user ) {
420        $archiveName = $this->getArchiveName();
421        $dstRel = $this->getArchiveRel( $archiveName );
422        $status = $this->publishTo( $srcPath, $dstRel );
423
424        if ( $status->isGood() &&
425            !$this->recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user )
426        ) {
427            $status->fatal( 'filenotfound', $srcPath );
428        }
429
430        return $status;
431    }
432
433    /**
434     * Record a file upload in the oldimage table, without adding log entries.
435     * @stable to override
436     *
437     * @param string $srcPath File system path to the source file
438     * @param string $archiveName The archive name of the file
439     * @param string $timestamp
440     * @param string $comment Upload comment
441     * @param UserIdentity $user User who did this upload
442     * @return bool
443     */
444    protected function recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user ) {
445        $dbw = $this->repo->getPrimaryDB();
446
447        $services = MediaWikiServices::getInstance();
448        $mwProps = new MWFileProps( $services->getMimeAnalyzer() );
449        $props = $mwProps->getPropsFromPath( $srcPath, true );
450        if ( !$props['fileExists'] ) {
451            return false;
452        }
453        $this->setProps( $props );
454
455        $dbw->startAtomic( __METHOD__ );
456
457        $commentFields = $services->getCommentStore()
458            ->insert( $dbw, 'oi_description', $comment );
459        $actorId = $services->getActorNormalization()
460            ->acquireActorId( $user, $dbw );
461        $dbw->newInsertQueryBuilder()
462            ->insertInto( 'oldimage' )
463            ->row( [
464                'oi_name' => $this->getName(),
465                'oi_archive_name' => $archiveName,
466                'oi_size' => $props['size'],
467                'oi_width' => intval( $props['width'] ),
468                'oi_height' => intval( $props['height'] ),
469                'oi_bits' => $props['bits'],
470                'oi_actor' => $actorId,
471                'oi_timestamp' => $dbw->timestamp( $timestamp ),
472                'oi_metadata' => $this->getMetadataForDb( $dbw ),
473                'oi_media_type' => $props['media_type'],
474                'oi_major_mime' => $props['major_mime'],
475                'oi_minor_mime' => $props['minor_mime'],
476                'oi_sha1' => $props['sha1'],
477            ] + $commentFields )
478            ->caller( __METHOD__ )->execute();
479
480        $migrationStage = MediaWikiServices::getInstance()->getMainConfig()->get(
481            MainConfigNames::FileSchemaMigrationStage
482        );
483        if ( $migrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
484            $commentFields = $services->getCommentStore()
485                ->insert( $dbw, 'fr_description', $comment );
486            $dbw->newInsertQueryBuilder()
487                ->insertInto( 'filerevision' )
488                ->ignore()
489                ->row( [
490                        'fr_file' => $this->acquireFileIdFromName(),
491                        'fr_size' => $this->size,
492                        'fr_width' => intval( $this->width ),
493                        'fr_height' => intval( $this->height ),
494                        'fr_bits' => $this->bits,
495                        'fr_actor' => $actorId,
496                        'fr_deleted' => 0,
497                        'fr_timestamp' => $dbw->timestamp( $timestamp ),
498                        'fr_metadata' => $this->getMetadataForDb( $dbw ),
499                        'fr_sha1' => $this->sha1
500                    ] + $commentFields )
501                ->caller( __METHOD__ )->execute();
502        }
503
504        $dbw->endAtomic( __METHOD__ );
505
506        return true;
507    }
508
509    /**
510     * If archive name is an empty string, then file does not "exist"
511     *
512     * This is the case for a couple files on Wikimedia servers where
513     * the old version is "lost".
514     * @return bool
515     */
516    public function exists() {
517        $archiveName = $this->getArchiveName();
518        if ( $archiveName === '' || !is_string( $archiveName ) ) {
519            return false;
520        }
521        return parent::exists();
522    }
523}
524
525/** @deprecated class alias since 1.44 */
526class_alias( OldLocalFile::class, 'OldLocalFile' );