Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
34.48% covered (danger)
34.48%
90 / 261
47.06% covered (danger)
47.06%
16 / 34
CRAP
0.00% covered (danger)
0.00%
0 / 1
LocalRepo
34.62% covered (danger)
34.62%
90 / 260
47.06% covered (danger)
47.06%
16 / 34
2617.75
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 newFileFromRow
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 newFromArchiveName
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getBackendOperationOptions
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 cleanupDeletedBatch
12.50% covered (danger)
12.50%
3 / 24
0.00% covered (danger)
0.00%
0 / 1
30.12
 deletedFileHasKey
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 hiddenFileHasKey
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 getHashFromKey
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 checkRedirect
92.59% covered (success)
92.59%
25 / 27
0.00% covered (danger)
0.00%
0 / 1
6.01
 findFiles
0.00% covered (danger)
0.00%
0 / 78
0.00% covered (danger)
0.00%
0 / 1
1056
 findBySha1
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 findBySha1s
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 findFilesByPrefix
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 getReplicaDB
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getPrimaryDB
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getDBFactory
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
2.86
 hasAccessibleSharedCache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getSharedCacheKey
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 invalidateImageRedirect
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 store
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 storeBatch
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 cleanupBatch
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 publish
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 publishBatch
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 delete
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 deleteBatch
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 skipWriteOperationIfSha1
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 isJsonMetadataEnabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isSplitMetadataEnabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 getSplitMetadataThreshold
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isMetadataUpdateEnabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isMetadataReserializeEnabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getBlobStore
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getUploadStash
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\FileRepo;
8
9use Closure;
10use InvalidArgumentException;
11use MediaWiki\Context\RequestContext;
12use MediaWiki\FileRepo\File\File;
13use MediaWiki\FileRepo\File\FileSelectQueryBuilder;
14use MediaWiki\FileRepo\File\LocalFile;
15use MediaWiki\FileRepo\File\OldLocalFile;
16use MediaWiki\Linker\LinkTarget;
17use MediaWiki\MediaWikiServices;
18use MediaWiki\Page\PageIdentity;
19use MediaWiki\Permissions\Authority;
20use MediaWiki\Status\Status;
21use MediaWiki\Storage\BlobStore;
22use MediaWiki\Title\Title;
23use MediaWiki\Upload\UploadStash;
24use MediaWiki\User\UserIdentity;
25use MediaWiki\WikiMap\WikiMap;
26use stdClass;
27use Wikimedia\ObjectCache\WANObjectCache;
28use Wikimedia\Rdbms\IConnectionProvider;
29use Wikimedia\Rdbms\IDatabase;
30use Wikimedia\Rdbms\IExpression;
31use Wikimedia\Rdbms\IReadableDatabase;
32use Wikimedia\Rdbms\IResultWrapper;
33use Wikimedia\Rdbms\LikeValue;
34
35/**
36 * Local repository that stores files in the local filesystem and registers them
37 * in the wiki's own database.
38 *
39 * This is the most commonly used file repository class.
40 *
41 * @ingroup FileRepo
42 * @method LocalFile|null newFile( $title, $time = false )
43 */
44class LocalRepo extends FileRepo {
45    /** @var callable */
46    protected $fileFactory = [ LocalFile::class, 'newFromTitle' ];
47    /** @var callable */
48    protected $fileFactoryKey = [ LocalFile::class, 'newFromKey' ];
49    /** @var callable */
50    protected $fileFromRowFactory = [ LocalFile::class, 'newFromRow' ];
51    /** @var callable */
52    protected $oldFileFromRowFactory = [ OldLocalFile::class, 'newFromRow' ];
53    /** @var callable */
54    protected $oldFileFactory = [ OldLocalFile::class, 'newFromTitle' ];
55    /** @var callable */
56    protected $oldFileFactoryKey = [ OldLocalFile::class, 'newFromKey' ];
57
58    /** @var string DB domain of the repo wiki */
59    protected $dbDomain;
60    protected IConnectionProvider $dbProvider;
61    /** @var bool Whether shared cache keys are exposed/accessible */
62    protected $hasAccessibleSharedCache;
63
64    /** @var BlobStore */
65    protected $blobStore;
66
67    /** @var bool */
68    protected $useJsonMetadata = true;
69
70    /** @var bool */
71    protected $useSplitMetadata = false;
72
73    /** @var int|null */
74    protected $splitMetadataThreshold = 1000;
75
76    /** @var bool */
77    protected $updateCompatibleMetadata = false;
78
79    /** @var bool */
80    protected $reserializeMetadata = false;
81
82    public function __construct( ?array $info = null ) {
83        parent::__construct( $info );
84
85        $this->dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
86        $this->hasAccessibleSharedCache = true;
87
88        $this->hasSha1Storage = ( $info['storageLayout'] ?? null ) === 'sha1';
89        $this->dbProvider = MediaWikiServices::getInstance()->getConnectionProvider();
90
91        if ( $this->hasSha1Storage() ) {
92            $this->backend = new FileBackendDBRepoWrapper( [
93                'backend'         => $this->backend,
94                'repoName'        => $this->name,
95                'dbHandleFactory' => $this->getDBFactory()
96            ] );
97        }
98
99        foreach (
100            [
101                'useJsonMetadata',
102                'useSplitMetadata',
103                'splitMetadataThreshold',
104                'updateCompatibleMetadata',
105                'reserializeMetadata',
106            ] as $option
107        ) {
108            if ( isset( $info[$option] ) ) {
109                $this->$option = $info[$option];
110            }
111        }
112    }
113
114    /**
115     * @param stdClass $row
116     * @return LocalFile
117     */
118    public function newFileFromRow( $row ) {
119        if ( isset( $row->img_name ) ) {
120            return ( $this->fileFromRowFactory )( $row, $this );
121        } elseif ( isset( $row->oi_name ) ) {
122            return ( $this->oldFileFromRowFactory )( $row, $this );
123        } else {
124            throw new InvalidArgumentException( __METHOD__ . ': invalid row' );
125        }
126    }
127
128    /**
129     * @param PageIdentity|LinkTarget|string $title
130     * @param string $archiveName
131     * @return OldLocalFile
132     */
133    public function newFromArchiveName( $title, $archiveName ) {
134        $title = File::normalizeTitle( $title );
135        return OldLocalFile::newFromArchiveName( $title, $this, $archiveName );
136    }
137
138    protected function getBackendOperationOptions(): array {
139        // See {@link LocalFile::acquireFileLock}
140        return [ 'nonLocking' => true ];
141    }
142
143    /**
144     * Delete files in the deleted directory if they are not referenced in the
145     * filearchive table. This needs to be done in the repo because it needs to
146     * interleave database locks with file operations, which is potentially a
147     * remote operation.
148     *
149     * @param string[] $storageKeys
150     *
151     * @return Status
152     */
153    public function cleanupDeletedBatch( array $storageKeys ) {
154        if ( $this->hasSha1Storage() ) {
155            wfDebug( __METHOD__ . ": skipped because storage uses sha1 paths" );
156            return Status::newGood();
157        }
158
159        $backend = $this->backend; // convenience
160        $root = $this->getZonePath( 'deleted' );
161        $dbw = $this->getPrimaryDB();
162        $status = $this->newGood();
163        $storageKeys = array_unique( $storageKeys );
164        foreach ( $storageKeys as $key ) {
165            $hashPath = $this->getDeletedHashPath( $key );
166            $path = "$root/$hashPath$key";
167            $dbw->startAtomic( __METHOD__ );
168            // Check for usage in deleted/hidden files and preemptively
169            // lock the key to avoid any future use until we are finished.
170            $deleted = $this->deletedFileHasKey( $key, 'lock' );
171            $hidden = $this->hiddenFileHasKey( $key, 'lock' );
172            if ( !$deleted && !$hidden ) { // not in use now
173                wfDebug( __METHOD__ . ": deleting $key" );
174                $op = [ 'op' => 'delete', 'src' => $path ];
175                if ( !$backend->doOperation( $op )->isOK() ) {
176                    $status->error( 'undelete-cleanup-error', $path );
177                    $status->failCount++;
178                }
179            } else {
180                wfDebug( __METHOD__ . "$key still in use" );
181                $status->successCount++;
182            }
183            $dbw->endAtomic( __METHOD__ );
184        }
185
186        return $status;
187    }
188
189    /**
190     * Check if a deleted (filearchive) file has this sha1 key
191     *
192     * @param string $key File storage key (base-36 sha1 key with file extension)
193     * @param string|null $lock Use "lock" to lock the row via FOR UPDATE
194     * @return bool File with this key is in use
195     */
196    protected function deletedFileHasKey( $key, $lock = null ) {
197        $queryBuilder = $this->getPrimaryDB()->newSelectQueryBuilder()
198            ->select( '1' )
199            ->from( 'filearchive' )
200            ->where( [ 'fa_storage_group' => 'deleted', 'fa_storage_key' => $key ] );
201        if ( $lock === 'lock' ) {
202            $queryBuilder->forUpdate();
203        }
204        return (bool)$queryBuilder->caller( __METHOD__ )->fetchField();
205    }
206
207    /**
208     * Check if a hidden (revision delete) file has this sha1 key
209     *
210     * @param string $key File storage key (base-36 sha1 key with file extension)
211     * @param string|null $lock Use "lock" to lock the row via FOR UPDATE
212     * @return bool File with this key is in use
213     */
214    protected function hiddenFileHasKey( $key, $lock = null ) {
215        $sha1 = self::getHashFromKey( $key );
216        $ext = File::normalizeExtension( substr( $key, strcspn( $key, '.' ) + 1 ) );
217
218        $dbw = $this->getPrimaryDB();
219        $queryBuilder = $dbw->newSelectQueryBuilder()
220            ->select( '1' )
221            ->from( 'oldimage' )
222            ->where( [
223                'oi_sha1' => $sha1,
224                $dbw->expr( 'oi_archive_name', IExpression::LIKE, new LikeValue( $dbw->anyString(), ".$ext" ) ),
225                $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE,
226            ] );
227        if ( $lock === 'lock' ) {
228            $queryBuilder->forUpdate();
229        }
230
231        return (bool)$queryBuilder->caller( __METHOD__ )->fetchField();
232    }
233
234    /**
235     * Gets the SHA1 hash from a storage key
236     *
237     * @param string $key
238     * @return string
239     */
240    public static function getHashFromKey( $key ) {
241        $sha1 = strtok( $key, '.' );
242        if ( is_string( $sha1 ) && strlen( $sha1 ) === 32 && $sha1[0] === '0' ) {
243            $sha1 = substr( $sha1, 1 );
244        }
245        return $sha1;
246    }
247
248    /**
249     * Checks if there is a redirect named as $title
250     *
251     * @param PageIdentity|LinkTarget $title Title of file
252     * @return Title|false
253     */
254    public function checkRedirect( $title ) {
255        $title = File::normalizeTitle( $title, 'exception' );
256
257        $memcKey = $this->getSharedCacheKey( 'file-redirect', md5( $title->getDBkey() ) );
258        if ( $memcKey === false ) {
259            $memcKey = $this->getLocalCacheKey( 'file-redirect', md5( $title->getDBkey() ) );
260            $expiry = 300; // no invalidation, 5 minutes
261        } else {
262            $expiry = 86400; // has invalidation, 1 day
263        }
264
265        $method = __METHOD__;
266        $redirDbKey = $this->wanCache->getWithSetCallback(
267            $memcKey,
268            $expiry,
269            function () use ( $method, $title ) {
270                $dbr = $this->getReplicaDB(); // possibly remote DB
271
272                $row = $dbr->newSelectQueryBuilder()
273                    ->select( [ 'rd_namespace', 'rd_title' ] )
274                    ->from( 'page' )
275                    ->join( 'redirect', null, 'rd_from = page_id' )
276                    ->where( [ 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey() ] )
277                    ->caller( $method )->fetchRow();
278
279                return ( $row && $row->rd_namespace == NS_FILE )
280                    ? Title::makeTitle( $row->rd_namespace, $row->rd_title )->getDBkey()
281                    : ''; // negative cache
282            },
283            [ 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
284        );
285
286        // @note: also checks " " for b/c
287        if ( $redirDbKey !== ' ' && strval( $redirDbKey ) !== '' ) {
288            // Page is a redirect to another file
289            return Title::newFromText( $redirDbKey, NS_FILE );
290        }
291
292        return false; // no redirect
293    }
294
295    /** @inheritDoc */
296    public function findFiles( array $items, $flags = 0 ) {
297        $finalFiles = []; // map of (DB key => corresponding File) for matches
298
299        $searchSet = []; // map of (normalized DB key => search params)
300        foreach ( $items as $item ) {
301            if ( is_array( $item ) ) {
302                $title = File::normalizeTitle( $item['title'] );
303                if ( $title ) {
304                    $searchSet[$title->getDBkey()] = $item;
305                }
306            } else {
307                $title = File::normalizeTitle( $item );
308                if ( $title ) {
309                    $searchSet[$title->getDBkey()] = [];
310                }
311            }
312        }
313
314        $fileMatchesSearch = static function ( File $file, array $search ) {
315            // Note: file name comparison done elsewhere (to handle redirects)
316
317            // Fallback to RequestContext::getMain should be replaced with a better
318            // way of setting the user that should be used; currently it needs to be
319            // set for each file individually. See T263033#6477586
320            $contextPerformer = RequestContext::getMain()->getAuthority();
321            $performer = ( !empty( $search['private'] ) && $search['private'] instanceof Authority )
322                ? $search['private']
323                : $contextPerformer;
324
325            return (
326                $file->exists() &&
327                (
328                    ( empty( $search['time'] ) && !$file->isOld() ) ||
329                    ( !empty( $search['time'] ) && $search['time'] === $file->getTimestamp() )
330                ) &&
331                ( !empty( $search['private'] ) || !$file->isDeleted( File::DELETED_FILE ) ) &&
332                $file->userCan( File::DELETED_FILE, $performer )
333            );
334        };
335
336        $applyMatchingFiles = function ( IResultWrapper $res, &$searchSet, &$finalFiles )
337            use ( $fileMatchesSearch, $flags )
338        {
339            $contLang = MediaWikiServices::getInstance()->getContentLanguage();
340            $info = $this->getInfo();
341            foreach ( $res as $row ) {
342                $file = $this->newFileFromRow( $row );
343                // There must have been a search for this DB key, but this has to handle the
344                // cases were title capitalization is different on the client and repo wikis.
345                $dbKeysLook = [ strtr( $file->getName(), ' ', '_' ) ];
346                if ( !empty( $info['initialCapital'] ) ) {
347                    // Search keys for "hi.png" and "Hi.png" should use the "Hi.png file"
348                    $dbKeysLook[] = $contLang->lcfirst( $file->getName() );
349                }
350                foreach ( $dbKeysLook as $dbKey ) {
351                    if ( isset( $searchSet[$dbKey] )
352                        && $fileMatchesSearch( $file, $searchSet[$dbKey] )
353                    ) {
354                        $finalFiles[$dbKey] = ( $flags & FileRepo::NAME_AND_TIME_ONLY )
355                            ? [ 'title' => $dbKey, 'timestamp' => $file->getTimestamp() ]
356                            : $file;
357                        unset( $searchSet[$dbKey] );
358                    }
359                }
360            }
361        };
362
363        $dbr = $this->getReplicaDB();
364
365        // Query image table
366        $imgNames = [];
367        foreach ( $searchSet as $dbKey => $_ ) {
368            $imgNames[] = $this->getNameFromTitle( File::normalizeTitle( $dbKey ) );
369        }
370
371        if ( count( $imgNames ) ) {
372            $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
373            $res = $queryBuilder->where( [ 'img_name' => $imgNames ] )->caller( __METHOD__ )->fetchResultSet();
374            $applyMatchingFiles( $res, $searchSet, $finalFiles );
375        }
376
377        // Query old image table
378        $oiConds = []; // WHERE clause array for each file
379        foreach ( $searchSet as $dbKey => $search ) {
380            if ( isset( $search['time'] ) ) {
381                $oiConds[] = $dbr
382                    ->expr( 'oi_name', '=', $this->getNameFromTitle( File::normalizeTitle( $dbKey ) ) )
383                    ->and( 'oi_timestamp', '=', $dbr->timestamp( $search['time'] ) );
384            }
385        }
386
387        if ( count( $oiConds ) ) {
388            $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr );
389
390            $res = $queryBuilder->where( $dbr->orExpr( $oiConds ) )
391                ->caller( __METHOD__ )->fetchResultSet();
392            $applyMatchingFiles( $res, $searchSet, $finalFiles );
393        }
394
395        // Check for redirects...
396        foreach ( $searchSet as $dbKey => $search ) {
397            if ( !empty( $search['ignoreRedirect'] ) ) {
398                continue;
399            }
400
401            $title = File::normalizeTitle( $dbKey );
402            $redir = $this->checkRedirect( $title ); // hopefully hits memcached
403
404            if ( $redir && $redir->getNamespace() === NS_FILE ) {
405                $file = $this->newFile( $redir );
406                if ( $file && $fileMatchesSearch( $file, $search ) ) {
407                    $file->redirectedFrom( $title->getDBkey() );
408                    if ( $flags & FileRepo::NAME_AND_TIME_ONLY ) {
409                        $finalFiles[$dbKey] = [
410                            'title' => $file->getTitle()->getDBkey(),
411                            'timestamp' => $file->getTimestamp()
412                        ];
413                    } else {
414                        $finalFiles[$dbKey] = $file;
415                    }
416                }
417            }
418        }
419
420        return $finalFiles;
421    }
422
423    /**
424     * Get an array or iterator of file objects for files that have a given
425     * SHA-1 content hash.
426     *
427     * @param string $hash A sha1 hash to look for
428     * @return LocalFile[]
429     */
430    public function findBySha1( $hash ) {
431        $queryBuilder = FileSelectQueryBuilder::newForFile( $this->getReplicaDB() );
432        $res = $queryBuilder->where( [ 'img_sha1' => $hash ] )
433            ->orderBy( 'img_name' )
434            ->caller( __METHOD__ )->fetchResultSet();
435
436        $result = [];
437        foreach ( $res as $row ) {
438            $result[] = $this->newFileFromRow( $row );
439        }
440        $res->free();
441
442        return $result;
443    }
444
445    /**
446     * Get an array of arrays or iterators of file objects for files that
447     * have the given SHA-1 content hashes.
448     *
449     * Overrides generic implementation in FileRepo for performance reason
450     *
451     * @param string[] $hashes An array of hashes
452     * @return File[][] An Array of arrays or iterators of file objects and the hash as key
453     */
454    public function findBySha1s( array $hashes ) {
455        if ( $hashes === [] ) {
456            return []; // empty parameter
457        }
458
459        $dbr = $this->getReplicaDB();
460        $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
461
462        $queryBuilder->where( [ 'img_sha1' => $hashes ] )
463            ->orderBy( 'img_name' );
464        $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
465
466        $result = [];
467        foreach ( $res as $row ) {
468            $file = $this->newFileFromRow( $row );
469            $result[$file->getSha1()][] = $file;
470        }
471        $res->free();
472
473        return $result;
474    }
475
476    /**
477     * Return an array of files where the name starts with $prefix.
478     *
479     * @param string $prefix The prefix to search for
480     * @param int $limit The maximum amount of files to return
481     * @return LocalFile[]
482     */
483    public function findFilesByPrefix( $prefix, $limit ) {
484        $dbr = $this->getReplicaDB();
485        $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
486
487        $queryBuilder
488            ->where( $dbr->expr( 'img_name', IExpression::LIKE, new LikeValue( $prefix, $dbr->anyString() ) ) )
489            ->orderBy( 'img_name' )
490            ->limit( intval( $limit ) );
491        $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
492
493        // Build file objects
494        $files = [];
495        foreach ( $res as $row ) {
496            $files[] = $this->newFileFromRow( $row );
497        }
498
499        return $files;
500    }
501
502    /**
503     * Get a connection to the replica DB
504     * @return IReadableDatabase
505     */
506    public function getReplicaDB() {
507        return $this->dbProvider->getReplicaDatabase();
508    }
509
510    /**
511     * Get a connection to the primary DB
512     * @return IDatabase
513     * @since 1.37
514     */
515    public function getPrimaryDB() {
516        return $this->dbProvider->getPrimaryDatabase();
517    }
518
519    /**
520     * Get a callback to get a DB handle given an index (DB_REPLICA/DB_PRIMARY)
521     * @return Closure
522     */
523    protected function getDBFactory() {
524        // TODO: DB_REPLICA/DB_PRIMARY shouldn't be passed around
525        return static function ( $index ) {
526            if ( $index === DB_PRIMARY ) {
527                return MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
528            } else {
529                return MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
530            }
531        };
532    }
533
534    /**
535     * Check whether the repo has a shared cache, accessible from the current site context
536     *
537     * @return bool
538     * @since 1.35
539     */
540    protected function hasAccessibleSharedCache() {
541        return $this->hasAccessibleSharedCache;
542    }
543
544    /** @inheritDoc */
545    public function getSharedCacheKey( $kClassSuffix, ...$components ) {
546        // T267668: do not include the repo name in the key
547        return $this->hasAccessibleSharedCache()
548            ? $this->wanCache->makeGlobalKey(
549                'filerepo-' . $kClassSuffix,
550                $this->dbDomain,
551                ...$components
552            )
553            : false;
554    }
555
556    /**
557     * Invalidates image redirect cache related to that image
558     *
559     * @param PageIdentity|LinkTarget $title Title of page
560     * @return void
561     */
562    public function invalidateImageRedirect( $title ) {
563        $key = $this->getSharedCacheKey( 'file-redirect', md5( $title->getDBkey() ) );
564        if ( $key ) {
565            $this->getPrimaryDB()->onTransactionPreCommitOrIdle(
566                function () use ( $key ) {
567                    $this->wanCache->delete( $key );
568                },
569                __METHOD__
570            );
571        }
572    }
573
574    /** @inheritDoc */
575    public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
576        return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
577    }
578
579    /** @inheritDoc */
580    public function storeBatch( array $triplets, $flags = 0 ) {
581        return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
582    }
583
584    /** @inheritDoc */
585    public function cleanupBatch( array $files, $flags = 0 ) {
586        return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
587    }
588
589    /** @inheritDoc */
590    public function publish(
591        $src,
592        $dstRel,
593        $archiveRel,
594        $flags = 0,
595        array $options = []
596    ) {
597        return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
598    }
599
600    /** @inheritDoc */
601    public function publishBatch( array $ntuples, $flags = 0 ) {
602        return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
603    }
604
605    /** @inheritDoc */
606    public function delete( $srcRel, $archiveRel ) {
607        return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
608    }
609
610    /** @inheritDoc */
611    public function deleteBatch( array $sourceDestPairs ) {
612        return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
613    }
614
615    /**
616     * Skips the write operation if storage is sha1-based, executes it normally otherwise
617     *
618     * @param string $function
619     * @param array $args
620     * @return Status
621     */
622    protected function skipWriteOperationIfSha1( $function, array $args ) {
623        $this->assertWritableRepo(); // fail out if read-only
624
625        if ( $this->hasSha1Storage() ) {
626            wfDebug( __METHOD__ . ": skipped because storage uses sha1 paths" );
627            return Status::newGood();
628        } else {
629            return parent::$function( ...$args );
630        }
631    }
632
633    /**
634     * Returns true if files should store metadata in JSON format. This
635     * requires metadata from all handlers to be JSON-serializable.
636     *
637     * To avoid breaking existing metadata, reading JSON metadata is always
638     * enabled regardless of this setting.
639     *
640     * @return bool
641     */
642    public function isJsonMetadataEnabled() {
643        return $this->useJsonMetadata;
644    }
645
646    /**
647     * Returns true if files should split up large metadata, storing parts of
648     * it in the BlobStore.
649     *
650     * @return bool
651     */
652    public function isSplitMetadataEnabled() {
653        return $this->isJsonMetadataEnabled() && $this->useSplitMetadata;
654    }
655
656    /**
657     * Get the threshold above which metadata items should be split into
658     * separate storage, or null if no splitting should be done.
659     *
660     * @return int
661     */
662    public function getSplitMetadataThreshold() {
663        return $this->splitMetadataThreshold;
664    }
665
666    /** @return bool */
667    public function isMetadataUpdateEnabled() {
668        return $this->updateCompatibleMetadata;
669    }
670
671    /** @return bool */
672    public function isMetadataReserializeEnabled() {
673        return $this->reserializeMetadata;
674    }
675
676    /**
677     * Get a BlobStore for storing and retrieving large metadata, or null if
678     * that can't be done.
679     */
680    public function getBlobStore(): ?BlobStore {
681        if ( !$this->blobStore ) {
682            $this->blobStore = MediaWikiServices::getInstance()->getBlobStoreFactory()
683                ->newBlobStore( $this->dbDomain );
684        }
685        return $this->blobStore;
686    }
687
688    /**
689     * Get an UploadStash associated with this repo.
690     *
691     * @param UserIdentity|null $user
692     * @return UploadStash
693     */
694    public function getUploadStash( ?UserIdentity $user = null ) {
695        return new UploadStash( $this, $user );
696    }
697}
698
699/** @deprecated class alias since 1.44 */
700class_alias( LocalRepo::class, 'LocalRepo' );