b209bd6750ddc082c66716f056aa91b9f5abeb55
[lhc/web/wiklou.git] / includes / filerepo / LocalRepo.php
1 <?php
2 /**
3 * Local repository that stores files in the local filesystem and registers them
4 * in the wiki's own database.
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 * @ingroup FileRepo
23 */
24
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.
28 *
29 * @ingroup FileRepo
30 */
31 class LocalRepo extends FileRepo {
32 /** @var bool */
33 protected $hasSha1Storage = false;
34
35 /** @var array */
36 protected $fileFactory = array( 'LocalFile', 'newFromTitle' );
37
38 /** @var array */
39 protected $fileFactoryKey = array( 'LocalFile', 'newFromKey' );
40
41 /** @var array */
42 protected $fileFromRowFactory = array( 'LocalFile', 'newFromRow' );
43
44 /** @var array */
45 protected $oldFileFromRowFactory = array( 'OldLocalFile', 'newFromRow' );
46
47 /** @var array */
48 protected $oldFileFactory = array( 'OldLocalFile', 'newFromTitle' );
49
50 /** @var array */
51 protected $oldFileFactoryKey = array( 'OldLocalFile', 'newFromKey' );
52
53 function __construct( array $info = null ) {
54 parent::__construct( $info );
55
56 $this->hasSha1Storage = isset( $info['storageLayout'] ) && $info['storageLayout'] === 'sha1';
57
58 if ( $this->hasSha1Storage() ) {
59 $this->backend = new FileBackendDBRepoWrapper( array(
60 'backend' => $this->backend,
61 'repoName' => $this->name,
62 'dbHandleFactory' => $this->getDBFactory()
63 ) );
64 }
65 }
66
67 /**
68 * @throws MWException
69 * @param stdClass $row
70 * @return LocalFile
71 */
72 function newFileFromRow( $row ) {
73 if ( isset( $row->img_name ) ) {
74 return call_user_func( $this->fileFromRowFactory, $row, $this );
75 } elseif ( isset( $row->oi_name ) ) {
76 return call_user_func( $this->oldFileFromRowFactory, $row, $this );
77 } else {
78 throw new MWException( __METHOD__ . ': invalid row' );
79 }
80 }
81
82 /**
83 * @param Title $title
84 * @param string $archiveName
85 * @return OldLocalFile
86 */
87 function newFromArchiveName( $title, $archiveName ) {
88 return OldLocalFile::newFromArchiveName( $title, $this, $archiveName );
89 }
90
91 /**
92 * Delete files in the deleted directory if they are not referenced in the
93 * filearchive table. This needs to be done in the repo because it needs to
94 * interleave database locks with file operations, which is potentially a
95 * remote operation.
96 *
97 * @param array $storageKeys
98 *
99 * @return FileRepoStatus
100 */
101 function cleanupDeletedBatch( array $storageKeys ) {
102 if ( $this->hasSha1Storage() ) {
103 wfDebug( __METHOD__ . ": skipped because storage uses sha1 paths\n" );
104 return Status::newGood();
105 }
106
107 $backend = $this->backend; // convenience
108 $root = $this->getZonePath( 'deleted' );
109 $dbw = $this->getMasterDB();
110 $status = $this->newGood();
111 $storageKeys = array_unique( $storageKeys );
112 foreach ( $storageKeys as $key ) {
113 $hashPath = $this->getDeletedHashPath( $key );
114 $path = "$root/$hashPath$key";
115 $dbw->startAtomic( __METHOD__ );
116 // Check for usage in deleted/hidden files and preemptively
117 // lock the key to avoid any future use until we are finished.
118 $deleted = $this->deletedFileHasKey( $key, 'lock' );
119 $hidden = $this->hiddenFileHasKey( $key, 'lock' );
120 if ( !$deleted && !$hidden ) { // not in use now
121 wfDebug( __METHOD__ . ": deleting $key\n" );
122 $op = array( 'op' => 'delete', 'src' => $path );
123 if ( !$backend->doOperation( $op )->isOK() ) {
124 $status->error( 'undelete-cleanup-error', $path );
125 $status->failCount++;
126 }
127 } else {
128 wfDebug( __METHOD__ . ": $key still in use\n" );
129 $status->successCount++;
130 }
131 $dbw->endAtomic( __METHOD__ );
132 }
133
134 return $status;
135 }
136
137 /**
138 * Check if a deleted (filearchive) file has this sha1 key
139 *
140 * @param string $key File storage key (base-36 sha1 key with file extension)
141 * @param string|null $lock Use "lock" to lock the row via FOR UPDATE
142 * @return bool File with this key is in use
143 */
144 protected function deletedFileHasKey( $key, $lock = null ) {
145 $options = ( $lock === 'lock' ) ? array( 'FOR UPDATE' ) : array();
146
147 $dbw = $this->getMasterDB();
148
149 return (bool)$dbw->selectField( 'filearchive', '1',
150 array( 'fa_storage_group' => 'deleted', 'fa_storage_key' => $key ),
151 __METHOD__, $options
152 );
153 }
154
155 /**
156 * Check if a hidden (revision delete) file has this sha1 key
157 *
158 * @param string $key File storage key (base-36 sha1 key with file extension)
159 * @param string|null $lock Use "lock" to lock the row via FOR UPDATE
160 * @return bool File with this key is in use
161 */
162 protected function hiddenFileHasKey( $key, $lock = null ) {
163 $options = ( $lock === 'lock' ) ? array( 'FOR UPDATE' ) : array();
164
165 $sha1 = self::getHashFromKey( $key );
166 $ext = File::normalizeExtension( substr( $key, strcspn( $key, '.' ) + 1 ) );
167
168 $dbw = $this->getMasterDB();
169
170 return (bool)$dbw->selectField( 'oldimage', '1',
171 array( 'oi_sha1' => $sha1,
172 'oi_archive_name ' . $dbw->buildLike( $dbw->anyString(), ".$ext" ),
173 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
174 __METHOD__, $options
175 );
176 }
177
178 /**
179 * Gets the SHA1 hash from a storage key
180 *
181 * @param string $key
182 * @return string
183 */
184 public static function getHashFromKey( $key ) {
185 return strtok( $key, '.' );
186 }
187
188 /**
189 * Checks if there is a redirect named as $title
190 *
191 * @param Title $title Title of file
192 * @return bool|Title
193 */
194 function checkRedirect( Title $title ) {
195 $cache = ObjectCache::getMainWANInstance();
196
197 $title = File::normalizeTitle( $title, 'exception' );
198
199 $memcKey = $this->getSharedCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
200 if ( $memcKey === false ) {
201 $memcKey = $this->getLocalCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
202 $expiry = 300; // no invalidation, 5 minutes
203 } else {
204 $expiry = 86400; // has invalidation, 1 day
205 }
206 $cachedValue = $cache->get( $memcKey );
207 if ( $cachedValue === ' ' || $cachedValue === '' ) {
208 // Does not exist
209 return false;
210 } elseif ( strval( $cachedValue ) !== '' && $cachedValue !== ' PURGED' ) {
211 return Title::newFromText( $cachedValue, NS_FILE );
212 } // else $cachedValue is false or null: cache miss
213
214 $id = $this->getArticleID( $title );
215 if ( !$id ) {
216 $cache->set( $memcKey, " ", $expiry );
217
218 return false;
219 }
220 $dbr = $this->getSlaveDB();
221 $row = $dbr->selectRow(
222 'redirect',
223 array( 'rd_title', 'rd_namespace' ),
224 array( 'rd_from' => $id ),
225 __METHOD__
226 );
227
228 if ( $row && $row->rd_namespace == NS_FILE ) {
229 $targetTitle = Title::makeTitle( $row->rd_namespace, $row->rd_title );
230 $cache->set( $memcKey, $targetTitle->getDBkey(), $expiry );
231
232 return $targetTitle;
233 } else {
234 $cache->set( $memcKey, '', $expiry );
235
236 return false;
237 }
238 }
239
240 /**
241 * Function link Title::getArticleID().
242 * We can't say Title object, what database it should use, so we duplicate that function here.
243 *
244 * @param Title $title
245 * @return bool|int|mixed
246 */
247 protected function getArticleID( $title ) {
248 if ( !$title instanceof Title ) {
249 return 0;
250 }
251 $dbr = $this->getSlaveDB();
252 $id = $dbr->selectField(
253 'page', // Table
254 'page_id', //Field
255 array( //Conditions
256 'page_namespace' => $title->getNamespace(),
257 'page_title' => $title->getDBkey(),
258 ),
259 __METHOD__ //Function name
260 );
261
262 return $id;
263 }
264
265 public function findFiles( array $items, $flags = 0 ) {
266 $finalFiles = array(); // map of (DB key => corresponding File) for matches
267
268 $searchSet = array(); // map of (normalized DB key => search params)
269 foreach ( $items as $item ) {
270 if ( is_array( $item ) ) {
271 $title = File::normalizeTitle( $item['title'] );
272 if ( $title ) {
273 $searchSet[$title->getDBkey()] = $item;
274 }
275 } else {
276 $title = File::normalizeTitle( $item );
277 if ( $title ) {
278 $searchSet[$title->getDBkey()] = array();
279 }
280 }
281 }
282
283 $fileMatchesSearch = function ( File $file, array $search ) {
284 // Note: file name comparison done elsewhere (to handle redirects)
285 $user = ( !empty( $search['private'] ) && $search['private'] instanceof User )
286 ? $search['private']
287 : null;
288
289 return (
290 $file->exists() &&
291 (
292 ( empty( $search['time'] ) && !$file->isOld() ) ||
293 ( !empty( $search['time'] ) && $search['time'] === $file->getTimestamp() )
294 ) &&
295 ( !empty( $search['private'] ) || !$file->isDeleted( File::DELETED_FILE ) ) &&
296 $file->userCan( File::DELETED_FILE, $user )
297 );
298 };
299
300 $that = $this;
301 $applyMatchingFiles = function ( ResultWrapper $res, &$searchSet, &$finalFiles )
302 use ( $that, $fileMatchesSearch, $flags )
303 {
304 global $wgContLang;
305 $info = $that->getInfo();
306 foreach ( $res as $row ) {
307 $file = $that->newFileFromRow( $row );
308 // There must have been a search for this DB key, but this has to handle the
309 // cases were title capitalization is different on the client and repo wikis.
310 $dbKeysLook = array( strtr( $file->getName(), ' ', '_' ) );
311 if ( !empty( $info['initialCapital'] ) ) {
312 // Search keys for "hi.png" and "Hi.png" should use the "Hi.png file"
313 $dbKeysLook[] = $wgContLang->lcfirst( $file->getName() );
314 }
315 foreach ( $dbKeysLook as $dbKey ) {
316 if ( isset( $searchSet[$dbKey] )
317 && $fileMatchesSearch( $file, $searchSet[$dbKey] )
318 ) {
319 $finalFiles[$dbKey] = ( $flags & FileRepo::NAME_AND_TIME_ONLY )
320 ? array( 'title' => $dbKey, 'timestamp' => $file->getTimestamp() )
321 : $file;
322 unset( $searchSet[$dbKey] );
323 }
324 }
325 }
326 };
327
328 $dbr = $this->getSlaveDB();
329
330 // Query image table
331 $imgNames = array();
332 foreach ( array_keys( $searchSet ) as $dbKey ) {
333 $imgNames[] = $this->getNameFromTitle( File::normalizeTitle( $dbKey ) );
334 }
335
336 if ( count( $imgNames ) ) {
337 $res = $dbr->select( 'image',
338 LocalFile::selectFields(), array( 'img_name' => $imgNames ), __METHOD__ );
339 $applyMatchingFiles( $res, $searchSet, $finalFiles );
340 }
341
342 // Query old image table
343 $oiConds = array(); // WHERE clause array for each file
344 foreach ( $searchSet as $dbKey => $search ) {
345 if ( isset( $search['time'] ) ) {
346 $oiConds[] = $dbr->makeList(
347 array(
348 'oi_name' => $this->getNameFromTitle( File::normalizeTitle( $dbKey ) ),
349 'oi_timestamp' => $dbr->timestamp( $search['time'] )
350 ),
351 LIST_AND
352 );
353 }
354 }
355
356 if ( count( $oiConds ) ) {
357 $res = $dbr->select( 'oldimage',
358 OldLocalFile::selectFields(), $dbr->makeList( $oiConds, LIST_OR ), __METHOD__ );
359 $applyMatchingFiles( $res, $searchSet, $finalFiles );
360 }
361
362 // Check for redirects...
363 foreach ( $searchSet as $dbKey => $search ) {
364 if ( !empty( $search['ignoreRedirect'] ) ) {
365 continue;
366 }
367
368 $title = File::normalizeTitle( $dbKey );
369 $redir = $this->checkRedirect( $title ); // hopefully hits memcached
370
371 if ( $redir && $redir->getNamespace() == NS_FILE ) {
372 $file = $this->newFile( $redir );
373 if ( $file && $fileMatchesSearch( $file, $search ) ) {
374 $file->redirectedFrom( $title->getDBkey() );
375 if ( $flags & FileRepo::NAME_AND_TIME_ONLY ) {
376 $finalFiles[$dbKey] = array(
377 'title' => $file->getTitle()->getDBkey(),
378 'timestamp' => $file->getTimestamp()
379 );
380 } else {
381 $finalFiles[$dbKey] = $file;
382 }
383 }
384 }
385 }
386
387 return $finalFiles;
388 }
389
390 /**
391 * Get an array or iterator of file objects for files that have a given
392 * SHA-1 content hash.
393 *
394 * @param string $hash A sha1 hash to look for
395 * @return File[]
396 */
397 function findBySha1( $hash ) {
398 $dbr = $this->getSlaveDB();
399 $res = $dbr->select(
400 'image',
401 LocalFile::selectFields(),
402 array( 'img_sha1' => $hash ),
403 __METHOD__,
404 array( 'ORDER BY' => 'img_name' )
405 );
406
407 $result = array();
408 foreach ( $res as $row ) {
409 $result[] = $this->newFileFromRow( $row );
410 }
411 $res->free();
412
413 return $result;
414 }
415
416 /**
417 * Get an array of arrays or iterators of file objects for files that
418 * have the given SHA-1 content hashes.
419 *
420 * Overrides generic implementation in FileRepo for performance reason
421 *
422 * @param array $hashes An array of hashes
423 * @return array An Array of arrays or iterators of file objects and the hash as key
424 */
425 function findBySha1s( array $hashes ) {
426 if ( !count( $hashes ) ) {
427 return array(); //empty parameter
428 }
429
430 $dbr = $this->getSlaveDB();
431 $res = $dbr->select(
432 'image',
433 LocalFile::selectFields(),
434 array( 'img_sha1' => $hashes ),
435 __METHOD__,
436 array( 'ORDER BY' => 'img_name' )
437 );
438
439 $result = array();
440 foreach ( $res as $row ) {
441 $file = $this->newFileFromRow( $row );
442 $result[$file->getSha1()][] = $file;
443 }
444 $res->free();
445
446 return $result;
447 }
448
449 /**
450 * Return an array of files where the name starts with $prefix.
451 *
452 * @param string $prefix The prefix to search for
453 * @param int $limit The maximum amount of files to return
454 * @return array
455 */
456 public function findFilesByPrefix( $prefix, $limit ) {
457 $selectOptions = array( 'ORDER BY' => 'img_name', 'LIMIT' => intval( $limit ) );
458
459 // Query database
460 $dbr = $this->getSlaveDB();
461 $res = $dbr->select(
462 'image',
463 LocalFile::selectFields(),
464 'img_name ' . $dbr->buildLike( $prefix, $dbr->anyString() ),
465 __METHOD__,
466 $selectOptions
467 );
468
469 // Build file objects
470 $files = array();
471 foreach ( $res as $row ) {
472 $files[] = $this->newFileFromRow( $row );
473 }
474
475 return $files;
476 }
477
478 /**
479 * Get a connection to the slave DB
480 * @return DatabaseBase
481 */
482 function getSlaveDB() {
483 return wfGetDB( DB_SLAVE );
484 }
485
486 /**
487 * Get a connection to the master DB
488 * @return DatabaseBase
489 */
490 function getMasterDB() {
491 return wfGetDB( DB_MASTER );
492 }
493
494 /**
495 * Get a callback to get a DB handle given an index (DB_SLAVE/DB_MASTER)
496 * @return Closure
497 */
498 protected function getDBFactory() {
499 return function( $index ) {
500 return wfGetDB( $index );
501 };
502 }
503
504 /**
505 * Get a key on the primary cache for this repository.
506 * Returns false if the repository's cache is not accessible at this site.
507 * The parameters are the parts of the key, as for wfMemcKey().
508 *
509 * @return string
510 */
511 function getSharedCacheKey( /*...*/ ) {
512 $args = func_get_args();
513
514 return call_user_func_array( 'wfMemcKey', $args );
515 }
516
517 /**
518 * Invalidates image redirect cache related to that image
519 *
520 * @param Title $title Title of page
521 * @return void
522 */
523 function invalidateImageRedirect( Title $title ) {
524 $key = $this->getSharedCacheKey( 'image_redirect', md5( $title->getDBkey() ) );
525 if ( $key ) {
526 $this->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
527 ObjectCache::getMainWANInstance()->delete( $key );
528 } );
529 }
530 }
531
532 /**
533 * Return information about the repository.
534 *
535 * @return array
536 * @since 1.22
537 */
538 function getInfo() {
539 global $wgFavicon;
540
541 return array_merge( parent::getInfo(), array(
542 'favicon' => wfExpandUrl( $wgFavicon ),
543 ) );
544 }
545
546 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
547 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
548 }
549
550 public function storeBatch( array $triplets, $flags = 0 ) {
551 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
552 }
553
554 public function cleanupBatch( array $files, $flags = 0 ) {
555 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
556 }
557
558 public function publish(
559 $srcPath,
560 $dstRel,
561 $archiveRel,
562 $flags = 0,
563 array $options = array()
564 ) {
565 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
566 }
567
568 public function publishBatch( array $ntuples, $flags = 0 ) {
569 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
570 }
571
572 public function delete( $srcRel, $archiveRel ) {
573 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
574 }
575
576 public function deleteBatch( array $sourceDestPairs ) {
577 return $this->skipWriteOperationIfSha1( __FUNCTION__, func_get_args() );
578 }
579
580 /**
581 * Skips the write operation if storage is sha1-based, executes it normally otherwise
582 *
583 * @param string $function
584 * @param array $args
585 * @return FileRepoStatus
586 */
587 protected function skipWriteOperationIfSha1( $function, array $args ) {
588 $this->assertWritableRepo(); // fail out if read-only
589
590 if ( $this->hasSha1Storage() ) {
591 wfDebug( __METHOD__ . ": skipped because storage uses sha1 paths\n" );
592 return Status::newGood();
593 } else {
594 return call_user_func_array( 'parent::' . $function, $args );
595 }
596 }
597 }