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
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.
31 class LocalRepo
extends FileRepo
{
33 protected $fileFactory = array( 'LocalFile', 'newFromTitle' );
36 protected $fileFactoryKey = array( 'LocalFile', 'newFromKey' );
39 protected $fileFromRowFactory = array( 'LocalFile', 'newFromRow' );
42 protected $oldFileFromRowFactory = array( 'OldLocalFile', 'newFromRow' );
45 protected $oldFileFactory = array( 'OldLocalFile', 'newFromTitle' );
48 protected $oldFileFactoryKey = array( 'OldLocalFile', 'newFromKey' );
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 );
61 throw new MWException( __METHOD__
. ': invalid row' );
67 * @param string $archiveName
68 * @return OldLocalFile
70 function newFromArchiveName( $title, $archiveName ) {
71 return OldLocalFile
::newFromArchiveName( $title, $this, $archiveName );
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
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++
;
106 wfDebug( __METHOD__
. ": $key still in use\n" );
107 $status->successCount++
;
109 $dbw->commit( __METHOD__
);
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 ),
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
),
157 * Gets the SHA1 hash from a storage key
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
172 function checkRedirect( Title
$title ) {
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
182 $expiry = 86400; // has invalidation, 1 day
184 $cachedValue = $wgMemc->get( $memcKey );
185 if ( $cachedValue === ' ' ||
$cachedValue === '' ) {
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 );
194 $wgMemc->add( $memcKey, " ", $expiry );
198 $dbr = $this->getSlaveDB();
199 $row = $dbr->selectRow(
201 array( 'rd_title', 'rd_namespace' ),
202 array( 'rd_from' => $id ),
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 );
212 $wgMemc->add( $memcKey, '', $expiry );
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
) {
229 $dbr = $this->getSlaveDB();
230 $id = $dbr->selectField(
234 'page_namespace' => $title->getNamespace(),
235 'page_title' => $title->getDBkey(),
237 __METHOD__
//Function name
243 public function findFiles( array $items, $flags = 0 ) {
244 $finalFiles = array(); // map of (DB key => corresponding File) for matches
246 $searchSet = array(); // map of (normalized DB key => search params)
247 foreach ( $items as $item ) {
248 if ( is_array( $item ) ) {
249 $title = File
::normalizeTitle( $item['title'] );
251 $searchSet[$title->getDBkey()] = $item;
254 $title = File
::normalizeTitle( $item );
256 $searchSet[$title->getDBkey()] = array();
261 $fileMatchesSearch = function ( File
$file, array $search ) {
262 // Note: file name comparison done elsewhere (to handle redirects)
263 $user = ( !empty( $search['private'] ) && $search['private'] instanceof User
)
270 ( empty( $search['time'] ) && !$file->isOld() ) ||
271 ( !empty( $search['time'] ) && $search['time'] === $file->getTimestamp() )
273 ( !empty( $search['private'] ) ||
!$file->isDeleted( File
::DELETED_FILE
) ) &&
274 $file->userCan( File
::DELETED_FILE
, $user )
279 $applyMatchingFiles = function ( ResultWrapper
$res, &$searchSet, &$finalFiles )
280 use ( $repo, $fileMatchesSearch, $flags )
283 $info = $repo->getInfo();
284 foreach ( $res as $row ) {
285 $file = $repo->newFileFromRow( $row );
286 // There must have been a search for this DB key, but this has to handle the
287 // cases were title capitalization is different on the client and repo wikis.
288 $dbKeysLook = array( str_replace( ' ', '_', $file->getName() ) );
289 if ( !empty( $info['initialCapital'] ) ) {
290 // Search keys for "hi.png" and "Hi.png" should use the "Hi.png file"
291 $dbKeysLook[] = $wgContLang->lcfirst( $file->getName() );
293 foreach ( $dbKeysLook as $dbKey ) {
294 if ( isset( $searchSet[$dbKey] )
295 && $fileMatchesSearch( $file, $searchSet[$dbKey] )
297 $finalFiles[$dbKey] = ( $flags & FileRepo
::NAME_AND_TIME_ONLY
)
298 ?
array( 'title' => $dbKey, 'timestamp' => $file->getTimestamp() )
300 unset( $searchSet[$dbKey] );
306 $dbr = $this->getSlaveDB();
310 foreach ( array_keys( $searchSet ) as $dbKey ) {
311 $imgNames[] = $this->getNameFromTitle( File
::normalizeTitle( $dbKey ) );
314 if ( count( $imgNames ) ) {
315 $res = $dbr->select( 'image',
316 LocalFile
::selectFields(), array( 'img_name' => $imgNames ), __METHOD__
);
317 $applyMatchingFiles( $res, $searchSet, $finalFiles );
320 // Query old image table
321 $oiConds = array(); // WHERE clause array for each file
322 foreach ( $searchSet as $dbKey => $search ) {
323 if ( isset( $search['time'] ) ) {
324 $oiConds[] = $dbr->makeList(
326 'oi_name' => $this->getNameFromTitle( File
::normalizeTitle( $dbKey ) ),
327 'oi_timestamp' => $dbr->timestamp( $search['time'] )
334 if ( count( $oiConds ) ) {
335 $res = $dbr->select( 'oldimage',
336 OldLocalFile
::selectFields(), $dbr->makeList( $oiConds, LIST_OR
), __METHOD__
);
337 $applyMatchingFiles( $res, $searchSet, $finalFiles );
340 // Check for redirects...
341 foreach ( $searchSet as $dbKey => $search ) {
342 if ( !empty( $search['ignoreRedirect'] ) ) {
346 $title = File
::normalizeTitle( $dbKey );
347 $redir = $this->checkRedirect( $title ); // hopefully hits memcached
349 if ( $redir && $redir->getNamespace() == NS_FILE
) {
350 $file = $this->newFile( $redir );
351 if ( $file && $fileMatchesSearch( $file, $search ) ) {
352 $file->redirectedFrom( $title->getDBkey() );
353 if ( $flags & FileRepo
::NAME_AND_TIME_ONLY
) {
354 $finalFiles[$dbKey] = array(
355 'title' => $file->getTitle()->getDBkey(),
356 'timestamp' => $file->getTimestamp()
359 $finalFiles[$dbKey] = $file;
369 * Get an array or iterator of file objects for files that have a given
370 * SHA-1 content hash.
372 * @param string $hash a sha1 hash to look for
375 function findBySha1( $hash ) {
376 $dbr = $this->getSlaveDB();
379 LocalFile
::selectFields(),
380 array( 'img_sha1' => $hash ),
382 array( 'ORDER BY' => 'img_name' )
386 foreach ( $res as $row ) {
387 $result[] = $this->newFileFromRow( $row );
395 * Get an array of arrays or iterators of file objects for files that
396 * have the given SHA-1 content hashes.
398 * Overrides generic implementation in FileRepo for performance reason
400 * @param array $hashes An array of hashes
401 * @return array An Array of arrays or iterators of file objects and the hash as key
403 function findBySha1s( array $hashes ) {
404 if ( !count( $hashes ) ) {
405 return array(); //empty parameter
408 $dbr = $this->getSlaveDB();
411 LocalFile
::selectFields(),
412 array( 'img_sha1' => $hashes ),
414 array( 'ORDER BY' => 'img_name' )
418 foreach ( $res as $row ) {
419 $file = $this->newFileFromRow( $row );
420 $result[$file->getSha1()][] = $file;
428 * Return an array of files where the name starts with $prefix.
430 * @param string $prefix The prefix to search for
431 * @param int $limit The maximum amount of files to return
434 public function findFilesByPrefix( $prefix, $limit ) {
435 $selectOptions = array( 'ORDER BY' => 'img_name', 'LIMIT' => intval( $limit ) );
438 $dbr = $this->getSlaveDB();
441 LocalFile
::selectFields(),
442 'img_name ' . $dbr->buildLike( $prefix, $dbr->anyString() ),
447 // Build file objects
449 foreach ( $res as $row ) {
450 $files[] = $this->newFileFromRow( $row );
457 * Get a connection to the slave DB
458 * @return DatabaseBase
460 function getSlaveDB() {
461 return wfGetDB( DB_SLAVE
);
465 * Get a connection to the master DB
466 * @return DatabaseBase
468 function getMasterDB() {
469 return wfGetDB( DB_MASTER
);
473 * Get a key on the primary cache for this repository.
474 * Returns false if the repository's cache is not accessible at this site.
475 * The parameters are the parts of the key, as for wfMemcKey().
479 function getSharedCacheKey( /*...*/ ) {
480 $args = func_get_args();
482 return call_user_func_array( 'wfMemcKey', $args );
486 * Invalidates image redirect cache related to that image
488 * @param Title $title Title of page
491 function invalidateImageRedirect( Title
$title ) {
493 $memcKey = $this->getSharedCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
495 // Set a temporary value for the cache key, to ensure
496 // that this value stays purged long enough so that
497 // it isn't refreshed with a stale value due to a
499 $wgMemc->set( $memcKey, ' PURGED', 12 );
504 * Return information about the repository.
512 return array_merge( parent
::getInfo(), array(
513 'favicon' => wfExpandUrl( $wgFavicon ),