Merge "Begin exposing SiteConfiguration via site contexts"
[mediawiki.git] / includes / filerepo / LocalRepo.php
blobaa851ffbf80d47f23bda822a27f58565afb7ac2e
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 /**
51 * @throws MWException
52 * @param array $row
53 * @return LocalFile
55 function newFileFromRow( $row ) {
56 if ( isset( $row->img_name ) ) {
57 return call_user_func( $this->fileFromRowFactory, $row, $this );
58 } elseif ( isset( $row->oi_name ) ) {
59 return call_user_func( $this->oldFileFromRowFactory, $row, $this );
60 } else {
61 throw new MWException( __METHOD__ . ': invalid row' );
65 /**
66 * @param Title $title
67 * @param string $archiveName
68 * @return OldLocalFile
70 function newFromArchiveName( $title, $archiveName ) {
71 return OldLocalFile::newFromArchiveName( $title, $this, $archiveName );
74 /**
75 * Delete files in the deleted directory if they are not referenced in the
76 * filearchive table. This needs to be done in the repo because it needs to
77 * interleave database locks with file operations, which is potentially a
78 * remote operation.
80 * @param array $storageKeys
82 * @return FileRepoStatus
84 function cleanupDeletedBatch( array $storageKeys ) {
85 $backend = $this->backend; // convenience
86 $root = $this->getZonePath( 'deleted' );
87 $dbw = $this->getMasterDB();
88 $status = $this->newGood();
89 $storageKeys = array_unique( $storageKeys );
90 foreach ( $storageKeys as $key ) {
91 $hashPath = $this->getDeletedHashPath( $key );
92 $path = "$root/$hashPath$key";
93 $dbw->begin( __METHOD__ );
94 // Check for usage in deleted/hidden files and pre-emptively
95 // lock the key to avoid any future use until we are finished.
96 $deleted = $this->deletedFileHasKey( $key, 'lock' );
97 $hidden = $this->hiddenFileHasKey( $key, 'lock' );
98 if ( !$deleted && !$hidden ) { // not in use now
99 wfDebug( __METHOD__ . ": deleting $key\n" );
100 $op = array( 'op' => 'delete', 'src' => $path );
101 if ( !$backend->doOperation( $op )->isOK() ) {
102 $status->error( 'undelete-cleanup-error', $path );
103 $status->failCount++;
105 } else {
106 wfDebug( __METHOD__ . ": $key still in use\n" );
107 $status->successCount++;
109 $dbw->commit( __METHOD__ );
112 return $status;
116 * Check if a deleted (filearchive) file has this sha1 key
118 * @param string $key File storage key (base-36 sha1 key with file extension)
119 * @param string|null $lock Use "lock" to lock the row via FOR UPDATE
120 * @return bool File with this key is in use
122 protected function deletedFileHasKey( $key, $lock = null ) {
123 $options = ( $lock === 'lock' ) ? array( 'FOR UPDATE' ) : array();
125 $dbw = $this->getMasterDB();
127 return (bool)$dbw->selectField( 'filearchive', '1',
128 array( 'fa_storage_group' => 'deleted', 'fa_storage_key' => $key ),
129 __METHOD__, $options
134 * Check if a hidden (revision delete) file has this sha1 key
136 * @param string $key File storage key (base-36 sha1 key with file extension)
137 * @param string|null $lock Use "lock" to lock the row via FOR UPDATE
138 * @return bool File with this key is in use
140 protected function hiddenFileHasKey( $key, $lock = null ) {
141 $options = ( $lock === 'lock' ) ? array( 'FOR UPDATE' ) : array();
143 $sha1 = self::getHashFromKey( $key );
144 $ext = File::normalizeExtension( substr( $key, strcspn( $key, '.' ) + 1 ) );
146 $dbw = $this->getMasterDB();
148 return (bool)$dbw->selectField( 'oldimage', '1',
149 array( 'oi_sha1' => $sha1,
150 'oi_archive_name ' . $dbw->buildLike( $dbw->anyString(), ".$ext" ),
151 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
152 __METHOD__, $options
157 * Gets the SHA1 hash from a storage key
159 * @param string $key
160 * @return string
162 public static function getHashFromKey( $key ) {
163 return strtok( $key, '.' );
167 * Checks if there is a redirect named as $title
169 * @param Title $title Title of file
170 * @return bool
172 function checkRedirect( Title $title ) {
173 global $wgMemc;
175 $title = File::normalizeTitle( $title, 'exception' );
177 $memcKey = $this->getSharedCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
178 if ( $memcKey === false ) {
179 $memcKey = $this->getLocalCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
180 $expiry = 300; // no invalidation, 5 minutes
181 } else {
182 $expiry = 86400; // has invalidation, 1 day
184 $cachedValue = $wgMemc->get( $memcKey );
185 if ( $cachedValue === ' ' || $cachedValue === '' ) {
186 // Does not exist
187 return false;
188 } elseif ( strval( $cachedValue ) !== '' && $cachedValue !== ' PURGED' ) {
189 return Title::newFromText( $cachedValue, NS_FILE );
190 } // else $cachedValue is false or null: cache miss
192 $id = $this->getArticleID( $title );
193 if ( !$id ) {
194 $wgMemc->add( $memcKey, " ", $expiry );
196 return false;
198 $dbr = $this->getSlaveDB();
199 $row = $dbr->selectRow(
200 'redirect',
201 array( 'rd_title', 'rd_namespace' ),
202 array( 'rd_from' => $id ),
203 __METHOD__
206 if ( $row && $row->rd_namespace == NS_FILE ) {
207 $targetTitle = Title::makeTitle( $row->rd_namespace, $row->rd_title );
208 $wgMemc->add( $memcKey, $targetTitle->getDBkey(), $expiry );
210 return $targetTitle;
211 } else {
212 $wgMemc->add( $memcKey, '', $expiry );
214 return false;
219 * Function link Title::getArticleID().
220 * We can't say Title object, what database it should use, so we duplicate that function here.
222 * @param Title $title
223 * @return bool|int|mixed
225 protected function getArticleID( $title ) {
226 if ( !$title instanceof Title ) {
227 return 0;
229 $dbr = $this->getSlaveDB();
230 $id = $dbr->selectField(
231 'page', // Table
232 'page_id', //Field
233 array( //Conditions
234 'page_namespace' => $title->getNamespace(),
235 'page_title' => $title->getDBkey(),
237 __METHOD__ //Function name
240 return $id;
243 public function findFiles( array $items ) {
244 $finalFiles = array(); // map of (DB key => corresponding File) for matches
246 $searchSet = array(); // map of (DB key => normalized search params)
247 foreach ( $items as $item ) {
248 $title = is_array( $item )
249 ? File::normalizeTitle( $item['title'] )
250 : File::normalizeTitle( $item );
251 if ( $title ) { // valid title
252 $searchSet[$title->getDbKey()] = ( is_array( $item ) ? $item : array() );
256 $fileMatchesSearch = function( File $file, array $search ) {
257 // Note: file name comparison done elsewhere (to handle redirects)
258 return (
259 $file->exists() &&
261 ( empty( $search['time'] ) && !$file->isOld() ) ||
262 ( !empty( $search['time'] ) && $search['time'] === $file->getTimestamp() )
263 ) &&
264 ( !empty( $search['private'] ) || !$file->isDeleted( File::DELETED_FILE ) ) &&
265 $file->userCan( File::DELETED_FILE )
269 $repo = $this;
270 $applyMatchingFiles = function( ResultWrapper $res, &$searchSet, &$finalFiles )
271 use ( $repo, $fileMatchesSearch )
273 foreach ( $res as $row ) {
274 $possFile = $repo->newFileFromRow( $row );
275 $dbKey = $possFile->getName();
276 // There must have been a search for this DB Key
277 if ( $fileMatchesSearch( $possFile, $searchSet[$dbKey] ) ) {
278 $finalFiles[$dbKey] = $possFile;
279 unset( $searchSet[$dbKey] );
284 $dbr = $this->getSlaveDB();
286 // Query image table
287 $imgNames = array_keys( $searchSet );
288 if ( count( $imgNames ) ) {
289 $res = $dbr->select( 'image',
290 LocalFile::selectFields(), array( 'img_name' => $imgNames ), __METHOD__ );
291 $applyMatchingFiles( $res, $searchSet, $finalFiles );
294 // Query old image table
295 $oiConds = array(); // WHERE clause array for each file
296 foreach ( $searchSet as $dbKey => $search ) {
297 if ( isset( $search['params']['time'] ) ) {
298 $oiConds[] = $dbr->makeList( array( 'oi_name' => $dbKey,
299 'oi_timestamp' => $dbr->timestamp( $search['params']['time'] ) ), LIST_AND );
302 if ( count( $oiConds ) ) {
303 $res = $dbr->select( 'oldimage',
304 OldLocalFile::selectFields(), $dbr->makeList( $oiConds, LIST_OR ), __METHOD__ );
305 $applyMatchingFiles( $res, $searchSet, $finalFiles );
308 // Check for redirects...
309 foreach ( $searchSet as $dbKey => $search ) {
310 if ( !empty( $search['ignoreRedirect'] ) ) {
311 continue;
313 $title = File::normalizeTitle( $dbKey );
314 $redir = $this->checkRedirect( $title ); // hopefully hits memcached
315 if ( $redir && $redir->getNamespace() == NS_FILE ) {
316 $possFile = $this->newFile( $redir );
317 if ( $possFile && $fileMatchesSearch( $possFile, $search ) ) {
318 $possFile->redirectedFrom( $title->getDBkey() );
319 $finalFiles[$dbKey] = $possFile;
324 return $finalFiles;
328 * Get an array or iterator of file objects for files that have a given
329 * SHA-1 content hash.
331 * @param string $hash a sha1 hash to look for
332 * @return array
334 function findBySha1( $hash ) {
335 $dbr = $this->getSlaveDB();
336 $res = $dbr->select(
337 'image',
338 LocalFile::selectFields(),
339 array( 'img_sha1' => $hash ),
340 __METHOD__,
341 array( 'ORDER BY' => 'img_name' )
344 $result = array();
345 foreach ( $res as $row ) {
346 $result[] = $this->newFileFromRow( $row );
348 $res->free();
350 return $result;
354 * Get an array of arrays or iterators of file objects for files that
355 * have the given SHA-1 content hashes.
357 * Overrides generic implementation in FileRepo for performance reason
359 * @param array $hashes An array of hashes
360 * @return array An Array of arrays or iterators of file objects and the hash as key
362 function findBySha1s( array $hashes ) {
363 if ( !count( $hashes ) ) {
364 return array(); //empty parameter
367 $dbr = $this->getSlaveDB();
368 $res = $dbr->select(
369 'image',
370 LocalFile::selectFields(),
371 array( 'img_sha1' => $hashes ),
372 __METHOD__,
373 array( 'ORDER BY' => 'img_name' )
376 $result = array();
377 foreach ( $res as $row ) {
378 $file = $this->newFileFromRow( $row );
379 $result[$file->getSha1()][] = $file;
381 $res->free();
383 return $result;
387 * Return an array of files where the name starts with $prefix.
389 * @param string $prefix The prefix to search for
390 * @param int $limit The maximum amount of files to return
391 * @return array
393 public function findFilesByPrefix( $prefix, $limit ) {
394 $selectOptions = array( 'ORDER BY' => 'img_name', 'LIMIT' => intval( $limit ) );
396 // Query database
397 $dbr = $this->getSlaveDB();
398 $res = $dbr->select(
399 'image',
400 LocalFile::selectFields(),
401 'img_name ' . $dbr->buildLike( $prefix, $dbr->anyString() ),
402 __METHOD__,
403 $selectOptions
406 // Build file objects
407 $files = array();
408 foreach ( $res as $row ) {
409 $files[] = $this->newFileFromRow( $row );
412 return $files;
416 * Get a connection to the slave DB
417 * @return DatabaseBase
419 function getSlaveDB() {
420 return wfGetDB( DB_SLAVE );
424 * Get a connection to the master DB
425 * @return DatabaseBase
427 function getMasterDB() {
428 return wfGetDB( DB_MASTER );
432 * Get a key on the primary cache for this repository.
433 * Returns false if the repository's cache is not accessible at this site.
434 * The parameters are the parts of the key, as for wfMemcKey().
436 * @return string
438 function getSharedCacheKey( /*...*/ ) {
439 $args = func_get_args();
441 return call_user_func_array( 'wfMemcKey', $args );
445 * Invalidates image redirect cache related to that image
447 * @param Title $title Title of page
448 * @return void
450 function invalidateImageRedirect( Title $title ) {
451 global $wgMemc;
452 $memcKey = $this->getSharedCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
453 if ( $memcKey ) {
454 // Set a temporary value for the cache key, to ensure
455 // that this value stays purged long enough so that
456 // it isn't refreshed with a stale value due to a
457 // lagged slave.
458 $wgMemc->set( $memcKey, ' PURGED', 12 );