Import: Handle uploads with sha1 starting with 0 properly
[mediawiki.git] / includes / filerepo / LocalRepo.php
blobe93a4a857a40cacaff455ba277b1dc3ab92a6bdc
1 <?php
2 /**
3 * Local repository that stores files in the local filesystem and registers them
4 * in the wiki's own database.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
21 * @file
22 * @ingroup FileRepo
25 /**
26 * A repository that stores files in the local filesystem and registers them
27 * in the wiki's own database. This is the most commonly used repository class.
29 * @ingroup FileRepo
31 class LocalRepo extends FileRepo {
32 /** @var array */
33 protected $fileFactory = array( 'LocalFile', 'newFromTitle' );
35 /** @var array */
36 protected $fileFactoryKey = array( 'LocalFile', 'newFromKey' );
38 /** @var array */
39 protected $fileFromRowFactory = array( 'LocalFile', 'newFromRow' );
41 /** @var array */
42 protected $oldFileFromRowFactory = array( 'OldLocalFile', 'newFromRow' );
44 /** @var array */
45 protected $oldFileFactory = array( 'OldLocalFile', 'newFromTitle' );
47 /** @var array */
48 protected $oldFileFactoryKey = array( 'OldLocalFile', 'newFromKey' );
50 function __construct( array $info = null ) {
51 parent::__construct( $info );
53 $this->hasSha1Storage = isset( $info['storageLayout'] ) && $info['storageLayout'] === 'sha1';
55 if ( $this->hasSha1Storage() ) {
56 $this->backend = new FileBackendDBRepoWrapper( array(
57 'backend' => $this->backend,
58 'repoName' => $this->name,
59 'dbHandleFactory' => $this->getDBFactory()
60 ) );
64 /**
65 * @throws MWException
66 * @param stdClass $row
67 * @return LocalFile
69 function newFileFromRow( $row ) {
70 if ( isset( $row->img_name ) ) {
71 return call_user_func( $this->fileFromRowFactory, $row, $this );
72 } elseif ( isset( $row->oi_name ) ) {
73 return call_user_func( $this->oldFileFromRowFactory, $row, $this );
74 } else {
75 throw new MWException( __METHOD__ . ': invalid row' );
79 /**
80 * @param Title $title
81 * @param string $archiveName
82 * @return OldLocalFile
84 function newFromArchiveName( $title, $archiveName ) {
85 return OldLocalFile::newFromArchiveName( $title, $this, $archiveName );
88 /**
89 * Delete files in the deleted directory if they are not referenced in the
90 * filearchive table. This needs to be done in the repo because it needs to
91 * interleave database locks with file operations, which is potentially a
92 * remote operation.
94 * @param array $storageKeys
96 * @return FileRepoStatus
98 function cleanupDeletedBatch( array $storageKeys ) {
99 if ( $this->hasSha1Storage() ) {
100 wfDebug( __METHOD__ . ": skipped because storage uses sha1 paths\n" );
101 return Status::newGood();
104 $backend = $this->backend; // convenience
105 $root = $this->getZonePath( 'deleted' );
106 $dbw = $this->getMasterDB();
107 $status = $this->newGood();
108 $storageKeys = array_unique( $storageKeys );
109 foreach ( $storageKeys as $key ) {
110 $hashPath = $this->getDeletedHashPath( $key );
111 $path = "$root/$hashPath$key";
112 $dbw->startAtomic( __METHOD__ );
113 // Check for usage in deleted/hidden files and preemptively
114 // lock the key to avoid any future use until we are finished.
115 $deleted = $this->deletedFileHasKey( $key, 'lock' );
116 $hidden = $this->hiddenFileHasKey( $key, 'lock' );
117 if ( !$deleted && !$hidden ) { // not in use now
118 wfDebug( __METHOD__ . ": deleting $key\n" );
119 $op = array( 'op' => 'delete', 'src' => $path );
120 if ( !$backend->doOperation( $op )->isOK() ) {
121 $status->error( 'undelete-cleanup-error', $path );
122 $status->failCount++;
124 } else {
125 wfDebug( __METHOD__ . ": $key still in use\n" );
126 $status->successCount++;
128 $dbw->endAtomic( __METHOD__ );
131 return $status;
135 * Check if a deleted (filearchive) file has this sha1 key
137 * @param string $key File storage key (base-36 sha1 key with file extension)
138 * @param string|null $lock Use "lock" to lock the row via FOR UPDATE
139 * @return bool File with this key is in use
141 protected function deletedFileHasKey( $key, $lock = null ) {
142 $options = ( $lock === 'lock' ) ? array( 'FOR UPDATE' ) : array();
144 $dbw = $this->getMasterDB();
146 return (bool)$dbw->selectField( 'filearchive', '1',
147 array( 'fa_storage_group' => 'deleted', 'fa_storage_key' => $key ),
148 __METHOD__, $options
153 * Check if a hidden (revision delete) file has this sha1 key
155 * @param string $key File storage key (base-36 sha1 key with file extension)
156 * @param string|null $lock Use "lock" to lock the row via FOR UPDATE
157 * @return bool File with this key is in use
159 protected function hiddenFileHasKey( $key, $lock = null ) {
160 $options = ( $lock === 'lock' ) ? array( 'FOR UPDATE' ) : array();
162 $sha1 = self::getHashFromKey( $key );
163 $ext = File::normalizeExtension( substr( $key, strcspn( $key, '.' ) + 1 ) );
165 $dbw = $this->getMasterDB();
167 return (bool)$dbw->selectField( 'oldimage', '1',
168 array( 'oi_sha1' => $sha1,
169 'oi_archive_name ' . $dbw->buildLike( $dbw->anyString(), ".$ext" ),
170 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
171 __METHOD__, $options
176 * Gets the SHA1 hash from a storage key
178 * @param string $key
179 * @return string
181 public static function getHashFromKey( $key ) {
182 return strtok( $key, '.' );
186 * Checks if there is a redirect named as $title
188 * @param Title $title Title of file
189 * @return bool|Title
191 function checkRedirect( Title $title ) {
192 $title = File::normalizeTitle( $title, 'exception' );
194 $memcKey = $this->getSharedCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
195 if ( $memcKey === false ) {
196 $memcKey = $this->getLocalCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
197 $expiry = 300; // no invalidation, 5 minutes
198 } else {
199 $expiry = 86400; // has invalidation, 1 day
202 $that = $this;
203 $redirDbKey = ObjectCache::getMainWANInstance()->getWithSetCallback(
204 $memcKey,
205 $expiry,
206 function ( $oldValue, &$ttl, array &$setOpts ) use ( $that, $title ) {
207 $dbr = $that->getSlaveDB(); // possibly remote DB
209 $setOpts += Database::getCacheSetOptions( $dbr );
211 if ( $title instanceof Title ) {
212 $row = $dbr->selectRow(
213 array( 'page', 'redirect' ),
214 array( 'rd_namespace', 'rd_title' ),
215 array(
216 'page_namespace' => $title->getNamespace(),
217 'page_title' => $title->getDBkey(),
218 'rd_from = page_id'
220 __METHOD__
222 } else {
223 $row = false;
226 return ( $row && $row->rd_namespace == NS_FILE )
227 ? Title::makeTitle( $row->rd_namespace, $row->rd_title )->getDBkey()
228 : ''; // negative cache
232 // @note: also checks " " for b/c
233 if ( $redirDbKey !== ' ' && strval( $redirDbKey ) !== '' ) {
234 // Page is a redirect to another file
235 return Title::newFromText( $redirDbKey, NS_FILE );
238 return false; // no redirect
241 public function findFiles( array $items, $flags = 0 ) {
242 $finalFiles = array(); // map of (DB key => corresponding File) for matches
244 $searchSet = array(); // map of (normalized DB key => search params)
245 foreach ( $items as $item ) {
246 if ( is_array( $item ) ) {
247 $title = File::normalizeTitle( $item['title'] );
248 if ( $title ) {
249 $searchSet[$title->getDBkey()] = $item;
251 } else {
252 $title = File::normalizeTitle( $item );
253 if ( $title ) {
254 $searchSet[$title->getDBkey()] = array();
259 $fileMatchesSearch = function ( File $file, array $search ) {
260 // Note: file name comparison done elsewhere (to handle redirects)
261 $user = ( !empty( $search['private'] ) && $search['private'] instanceof User )
262 ? $search['private']
263 : null;
265 return (
266 $file->exists() &&
268 ( empty( $search['time'] ) && !$file->isOld() ) ||
269 ( !empty( $search['time'] ) && $search['time'] === $file->getTimestamp() )
270 ) &&
271 ( !empty( $search['private'] ) || !$file->isDeleted( File::DELETED_FILE ) ) &&
272 $file->userCan( File::DELETED_FILE, $user )
276 $that = $this;
277 $applyMatchingFiles = function ( ResultWrapper $res, &$searchSet, &$finalFiles )
278 use ( $that, $fileMatchesSearch, $flags )
280 global $wgContLang;
281 $info = $that->getInfo();
282 foreach ( $res as $row ) {
283 $file = $that->newFileFromRow( $row );
284 // There must have been a search for this DB key, but this has to handle the
285 // cases were title capitalization is different on the client and repo wikis.
286 $dbKeysLook = array( strtr( $file->getName(), ' ', '_' ) );
287 if ( !empty( $info['initialCapital'] ) ) {
288 // Search keys for "hi.png" and "Hi.png" should use the "Hi.png file"
289 $dbKeysLook[] = $wgContLang->lcfirst( $file->getName() );
291 foreach ( $dbKeysLook as $dbKey ) {
292 if ( isset( $searchSet[$dbKey] )
293 && $fileMatchesSearch( $file, $searchSet[$dbKey] )
295 $finalFiles[$dbKey] = ( $flags & FileRepo::NAME_AND_TIME_ONLY )
296 ? array( 'title' => $dbKey, 'timestamp' => $file->getTimestamp() )
297 : $file;
298 unset( $searchSet[$dbKey] );
304 $dbr = $this->getSlaveDB();
306 // Query image table
307 $imgNames = array();
308 foreach ( array_keys( $searchSet ) as $dbKey ) {
309 $imgNames[] = $this->getNameFromTitle( File::normalizeTitle( $dbKey ) );
312 if ( count( $imgNames ) ) {
313 $res = $dbr->select( 'image',
314 LocalFile::selectFields(), array( 'img_name' => $imgNames ), __METHOD__ );
315 $applyMatchingFiles( $res, $searchSet, $finalFiles );
318 // Query old image table
319 $oiConds = array(); // WHERE clause array for each file
320 foreach ( $searchSet as $dbKey => $search ) {
321 if ( isset( $search['time'] ) ) {
322 $oiConds[] = $dbr->makeList(
323 array(
324 'oi_name' => $this->getNameFromTitle( File::normalizeTitle( $dbKey ) ),
325 'oi_timestamp' => $dbr->timestamp( $search['time'] )
327 LIST_AND
332 if ( count( $oiConds ) ) {
333 $res = $dbr->select( 'oldimage',
334 OldLocalFile::selectFields(), $dbr->makeList( $oiConds, LIST_OR ), __METHOD__ );
335 $applyMatchingFiles( $res, $searchSet, $finalFiles );
338 // Check for redirects...
339 foreach ( $searchSet as $dbKey => $search ) {
340 if ( !empty( $search['ignoreRedirect'] ) ) {
341 continue;
344 $title = File::normalizeTitle( $dbKey );
345 $redir = $this->checkRedirect( $title ); // hopefully hits memcached
347 if ( $redir && $redir->getNamespace() == NS_FILE ) {
348 $file = $this->newFile( $redir );
349 if ( $file && $fileMatchesSearch( $file, $search ) ) {
350 $file->redirectedFrom( $title->getDBkey() );
351 if ( $flags & FileRepo::NAME_AND_TIME_ONLY ) {
352 $finalFiles[$dbKey] = array(
353 'title' => $file->getTitle()->getDBkey(),
354 'timestamp' => $file->getTimestamp()
356 } else {
357 $finalFiles[$dbKey] = $file;
363 return $finalFiles;
367 * Get an array or iterator of file objects for files that have a given
368 * SHA-1 content hash.
370 * @param string $hash A sha1 hash to look for
371 * @return File[]
373 function findBySha1( $hash ) {
374 $dbr = $this->getSlaveDB();
375 $res = $dbr->select(
376 'image',
377 LocalFile::selectFields(),
378 array( 'img_sha1' => $hash ),
379 __METHOD__,
380 array( 'ORDER BY' => 'img_name' )
383 $result = array();
384 foreach ( $res as $row ) {
385 $result[] = $this->newFileFromRow( $row );
387 $res->free();
389 return $result;
393 * Get an array of arrays or iterators of file objects for files that
394 * have the given SHA-1 content hashes.
396 * Overrides generic implementation in FileRepo for performance reason
398 * @param array $hashes An array of hashes
399 * @return array An Array of arrays or iterators of file objects and the hash as key
401 function findBySha1s( array $hashes ) {
402 if ( !count( $hashes ) ) {
403 return array(); // empty parameter
406 $dbr = $this->getSlaveDB();
407 $res = $dbr->select(
408 'image',
409 LocalFile::selectFields(),
410 array( 'img_sha1' => $hashes ),
411 __METHOD__,
412 array( 'ORDER BY' => 'img_name' )
415 $result = array();
416 foreach ( $res as $row ) {
417 $file = $this->newFileFromRow( $row );
418 $result[$file->getSha1()][] = $file;
420 $res->free();
422 return $result;
426 * Return an array of files where the name starts with $prefix.
428 * @param string $prefix The prefix to search for
429 * @param int $limit The maximum amount of files to return
430 * @return array
432 public function findFilesByPrefix( $prefix, $limit ) {
433 $selectOptions = array( 'ORDER BY' => 'img_name', 'LIMIT' => intval( $limit ) );
435 // Query database
436 $dbr = $this->getSlaveDB();
437 $res = $dbr->select(
438 'image',
439 LocalFile::selectFields(),
440 'img_name ' . $dbr->buildLike( $prefix, $dbr->anyString() ),
441 __METHOD__,
442 $selectOptions
445 // Build file objects
446 $files = array();
447 foreach ( $res as $row ) {
448 $files[] = $this->newFileFromRow( $row );
451 return $files;
455 * Get a connection to the slave DB
456 * @return DatabaseBase
458 function getSlaveDB() {
459 return wfGetDB( DB_SLAVE );
463 * Get a connection to the master DB
464 * @return DatabaseBase
466 function getMasterDB() {
467 return wfGetDB( DB_MASTER );
471 * Get a callback to get a DB handle given an index (DB_SLAVE/DB_MASTER)
472 * @return Closure
474 protected function getDBFactory() {
475 return function( $index ) {
476 return wfGetDB( $index );
481 * Get a key on the primary cache for this repository.
482 * Returns false if the repository's cache is not accessible at this site.
483 * The parameters are the parts of the key, as for wfMemcKey().
485 * @return string
487 function getSharedCacheKey( /*...*/ ) {
488 $args = func_get_args();
490 return call_user_func_array( 'wfMemcKey', $args );
494 * Invalidates image redirect cache related to that image
496 * @param Title $title Title of page
497 * @return void
499 function invalidateImageRedirect( Title $title ) {
500 $key = $this->getSharedCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
501 if ( $key ) {
502 $this->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
503 ObjectCache::getMainWANInstance()->delete( $key );
504 } );
509 * Return information about the repository.
511 * @return array
512 * @since 1.22
514 function getInfo() {
515 global $wgFavicon;
517 return array_merge( parent::getInfo(), array(
518 'favicon' => wfExpandUrl( $wgFavicon ),
519 ) );
522 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
523 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
526 public function storeBatch( array $triplets, $flags = 0 ) {
527 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
530 public function cleanupBatch( array $files, $flags = 0 ) {
531 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
534 public function publish(
535 $srcPath,
536 $dstRel,
537 $archiveRel,
538 $flags = 0,
539 array $options = array()
541 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
544 public function publishBatch( array $ntuples, $flags = 0 ) {
545 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
548 public function delete( $srcRel, $archiveRel ) {
549 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
552 public function deleteBatch( array $sourceDestPairs ) {
553 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
557 * Skips the write operation if storage is sha1-based, executes it normally otherwise
559 * @param string $function
560 * @param array $args
561 * @return FileRepoStatus
563 protected function skipWriteOperationIfSha1( $function, array $args ) {
564 $this->assertWritableRepo(); // fail out if read-only
566 if ( $this->hasSha1Storage() ) {
567 wfDebug( __METHOD__ . ": skipped because storage uses sha1 paths\n" );
568 return Status::newGood();
569 } else {
570 return call_user_func_array( 'parent::' . $function, $args );