MediaWiki REL1_32
FileBackendMultiWrite.php
Go to the documentation of this file.
1<?php
45 protected $backends = [];
46
48 protected $masterIndex = -1;
50 protected $readIndex = -1;
51
53 protected $syncChecks = 0;
55 protected $autoResync = false;
56
58 protected $asyncWrites = false;
59
60 /* Possible internal backend consistency checks */
61 const CHECK_SIZE = 1;
62 const CHECK_TIME = 2;
63 const CHECK_SHA1 = 4;
64
96 public function __construct( array $config ) {
97 parent::__construct( $config );
98 $this->syncChecks = $config['syncChecks'] ?? self::CHECK_SIZE;
99 $this->autoResync = $config['autoResync'] ?? false;
100 $this->asyncWrites = isset( $config['replication'] ) && $config['replication'] === 'async';
101 // Construct backends here rather than via registration
102 // to keep these backends hidden from outside the proxy.
103 $namesUsed = [];
104 foreach ( $config['backends'] as $index => $config ) {
105 $name = $config['name'];
106 if ( isset( $namesUsed[$name] ) ) { // don't break FileOp predicates
107 throw new LogicException( "Two or more backends defined with the name $name." );
108 }
109 $namesUsed[$name] = 1;
110 // Alter certain sub-backend settings for sanity
111 unset( $config['readOnly'] ); // use proxy backend setting
112 unset( $config['fileJournal'] ); // use proxy backend journal
113 unset( $config['lockManager'] ); // lock under proxy backend
114 $config['domainId'] = $this->domainId; // use the proxy backend wiki ID
115 if ( !empty( $config['isMultiMaster'] ) ) {
116 if ( $this->masterIndex >= 0 ) {
117 throw new LogicException( 'More than one master backend defined.' );
118 }
119 $this->masterIndex = $index; // this is the "master"
120 $config['fileJournal'] = $this->fileJournal; // log under proxy backend
121 }
122 if ( !empty( $config['readAffinity'] ) ) {
123 $this->readIndex = $index; // prefer this for reads
124 }
125 // Create sub-backend object
126 if ( !isset( $config['class'] ) ) {
127 throw new InvalidArgumentException( 'No class given for a backend config.' );
128 }
129 $class = $config['class'];
130 $this->backends[$index] = new $class( $config );
131 }
132 if ( $this->masterIndex < 0 ) { // need backends and must have a master
133 throw new LogicException( 'No master backend defined.' );
134 }
135 if ( $this->readIndex < 0 ) {
136 $this->readIndex = $this->masterIndex; // default
137 }
138 }
139
140 final protected function doOperationsInternal( array $ops, array $opts ) {
141 $status = $this->newStatus();
142
143 $mbe = $this->backends[$this->masterIndex]; // convenience
144
145 // Try to lock those files for the scope of this function...
146 $scopeLock = null;
147 if ( empty( $opts['nonLocking'] ) ) {
148 // Try to lock those files for the scope of this function...
150 $scopeLock = $this->getScopedLocksForOps( $ops, $status );
151 if ( !$status->isOK() ) {
152 return $status; // abort
153 }
154 }
155 // Clear any cache entries (after locks acquired)
156 $this->clearCache();
157 $opts['preserveCache'] = true; // only locked files are cached
158 // Get the list of paths to read/write...
159 $relevantPaths = $this->fileStoragePathsForOps( $ops );
160 // Check if the paths are valid and accessible on all backends...
161 $status->merge( $this->accessibilityCheck( $relevantPaths ) );
162 if ( !$status->isOK() ) {
163 return $status; // abort
164 }
165 // Do a consistency check to see if the backends are consistent...
166 $syncStatus = $this->consistencyCheck( $relevantPaths );
167 if ( !$syncStatus->isOK() ) {
168 wfDebugLog( 'FileOperation', static::class .
169 " failed sync check: " . FormatJson::encode( $relevantPaths ) );
170 // Try to resync the clone backends to the master on the spot...
171 if ( $this->autoResync === false
172 || !$this->resyncFiles( $relevantPaths, $this->autoResync )->isOK()
173 ) {
174 $status->merge( $syncStatus );
175
176 return $status; // abort
177 }
178 }
179 // Actually attempt the operation batch on the master backend...
180 $realOps = $this->substOpBatchPaths( $ops, $mbe );
181 $masterStatus = $mbe->doOperations( $realOps, $opts );
182 $status->merge( $masterStatus );
183 // Propagate the operations to the clone backends if there were no unexpected errors
184 // and if there were either no expected errors or if the 'force' option was used.
185 // However, if nothing succeeded at all, then don't replicate any of the operations.
186 // If $ops only had one operation, this might avoid backend sync inconsistencies.
187 if ( $masterStatus->isOK() && $masterStatus->successCount > 0 ) {
188 foreach ( $this->backends as $index => $backend ) {
189 if ( $index === $this->masterIndex ) {
190 continue; // done already
191 }
192
193 $realOps = $this->substOpBatchPaths( $ops, $backend );
194 if ( $this->asyncWrites && !$this->hasVolatileSources( $ops ) ) {
195 // Bind $scopeLock to the callback to preserve locks
196 DeferredUpdates::addCallableUpdate(
197 function () use ( $backend, $realOps, $opts, $scopeLock, $relevantPaths ) {
198 wfDebugLog( 'FileOperationReplication',
199 "'{$backend->getName()}' async replication; paths: " .
200 FormatJson::encode( $relevantPaths ) );
201 $backend->doOperations( $realOps, $opts );
202 }
203 );
204 } else {
205 wfDebugLog( 'FileOperationReplication',
206 "'{$backend->getName()}' sync replication; paths: " .
207 FormatJson::encode( $relevantPaths ) );
208 $status->merge( $backend->doOperations( $realOps, $opts ) );
209 }
210 }
211 }
212 // Make 'success', 'successCount', and 'failCount' fields reflect
213 // the overall operation, rather than all the batches for each backend.
214 // Do this by only using success values from the master backend's batch.
215 $status->success = $masterStatus->success;
216 $status->successCount = $masterStatus->successCount;
217 $status->failCount = $masterStatus->failCount;
218
219 return $status;
220 }
221
228 public function consistencyCheck( array $paths ) {
229 $status = $this->newStatus();
230 if ( $this->syncChecks == 0 || count( $this->backends ) <= 1 ) {
231 return $status; // skip checks
232 }
233
234 // Preload all of the stat info in as few round trips as possible...
235 foreach ( $this->backends as $backend ) {
236 $realPaths = $this->substPaths( $paths, $backend );
237 $backend->preloadFileStat( [ 'srcs' => $realPaths, 'latest' => true ] );
238 }
239
240 $mBackend = $this->backends[$this->masterIndex];
241 foreach ( $paths as $path ) {
242 $params = [ 'src' => $path, 'latest' => true ];
243 $mParams = $this->substOpPaths( $params, $mBackend );
244 // Stat the file on the 'master' backend
245 $mStat = $mBackend->getFileStat( $mParams );
246 if ( $this->syncChecks & self::CHECK_SHA1 ) {
247 $mSha1 = $mBackend->getFileSha1Base36( $mParams );
248 } else {
249 $mSha1 = false;
250 }
251 // Check if all clone backends agree with the master...
252 foreach ( $this->backends as $index => $cBackend ) {
253 if ( $index === $this->masterIndex ) {
254 continue; // master
255 }
256 $cParams = $this->substOpPaths( $params, $cBackend );
257 $cStat = $cBackend->getFileStat( $cParams );
258 if ( $mStat ) { // file is in master
259 if ( !$cStat ) { // file should exist
260 $status->fatal( 'backend-fail-synced', $path );
261 continue;
262 }
263 if ( $this->syncChecks & self::CHECK_SIZE ) {
264 if ( $cStat['size'] != $mStat['size'] ) { // wrong size
265 $status->fatal( 'backend-fail-synced', $path );
266 continue;
267 }
268 }
269 if ( $this->syncChecks & self::CHECK_TIME ) {
270 $mTs = wfTimestamp( TS_UNIX, $mStat['mtime'] );
271 $cTs = wfTimestamp( TS_UNIX, $cStat['mtime'] );
272 if ( abs( $mTs - $cTs ) > 30 ) { // outdated file somewhere
273 $status->fatal( 'backend-fail-synced', $path );
274 continue;
275 }
276 }
277 if ( $this->syncChecks & self::CHECK_SHA1 ) {
278 if ( $cBackend->getFileSha1Base36( $cParams ) !== $mSha1 ) { // wrong SHA1
279 $status->fatal( 'backend-fail-synced', $path );
280 continue;
281 }
282 }
283 } else { // file is not in master
284 if ( $cStat ) { // file should not exist
285 $status->fatal( 'backend-fail-synced', $path );
286 }
287 }
288 }
289 }
290
291 return $status;
292 }
293
300 public function accessibilityCheck( array $paths ) {
301 $status = $this->newStatus();
302 if ( count( $this->backends ) <= 1 ) {
303 return $status; // skip checks
304 }
305
306 foreach ( $paths as $path ) {
307 foreach ( $this->backends as $backend ) {
308 $realPath = $this->substPaths( $path, $backend );
309 if ( !$backend->isPathUsableInternal( $realPath ) ) {
310 $status->fatal( 'backend-fail-usable', $path );
311 }
312 }
313 }
314
315 return $status;
316 }
317
326 public function resyncFiles( array $paths, $resyncMode = true ) {
327 $status = $this->newStatus();
328
329 $mBackend = $this->backends[$this->masterIndex];
330 foreach ( $paths as $path ) {
331 $mPath = $this->substPaths( $path, $mBackend );
332 $mSha1 = $mBackend->getFileSha1Base36( [ 'src' => $mPath, 'latest' => true ] );
333 $mStat = $mBackend->getFileStat( [ 'src' => $mPath, 'latest' => true ] );
334 if ( $mStat === null || ( $mSha1 !== false && !$mStat ) ) { // sanity
335 $status->fatal( 'backend-fail-internal', $this->name );
336 wfDebugLog( 'FileOperation', __METHOD__
337 . ': File is not available on the master backend' );
338 continue; // file is not available on the master backend...
339 }
340 // Check of all clone backends agree with the master...
341 foreach ( $this->backends as $index => $cBackend ) {
342 if ( $index === $this->masterIndex ) {
343 continue; // master
344 }
345 $cPath = $this->substPaths( $path, $cBackend );
346 $cSha1 = $cBackend->getFileSha1Base36( [ 'src' => $cPath, 'latest' => true ] );
347 $cStat = $cBackend->getFileStat( [ 'src' => $cPath, 'latest' => true ] );
348 if ( $cStat === null || ( $cSha1 !== false && !$cStat ) ) { // sanity
349 $status->fatal( 'backend-fail-internal', $cBackend->getName() );
350 wfDebugLog( 'FileOperation', __METHOD__ .
351 ': File is not available on the clone backend' );
352 continue; // file is not available on the clone backend...
353 }
354 if ( $mSha1 === $cSha1 ) {
355 // already synced; nothing to do
356 } elseif ( $mSha1 !== false ) { // file is in master
357 if ( $resyncMode === 'conservative'
358 && $cStat && $cStat['mtime'] > $mStat['mtime']
359 ) {
360 $status->fatal( 'backend-fail-synced', $path );
361 continue; // don't rollback data
362 }
363 $fsFile = $mBackend->getLocalReference(
364 [ 'src' => $mPath, 'latest' => true ] );
365 $status->merge( $cBackend->quickStore(
366 [ 'src' => $fsFile->getPath(), 'dst' => $cPath ]
367 ) );
368 } elseif ( $mStat === false ) { // file is not in master
369 if ( $resyncMode === 'conservative' ) {
370 $status->fatal( 'backend-fail-synced', $path );
371 continue; // don't delete data
372 }
373 $status->merge( $cBackend->quickDelete( [ 'src' => $cPath ] ) );
374 }
375 }
376 }
377
378 if ( !$status->isOK() ) {
379 wfDebugLog( 'FileOperation', static::class .
380 " failed to resync: " . FormatJson::encode( $paths ) );
381 }
382
383 return $status;
384 }
385
392 protected function fileStoragePathsForOps( array $ops ) {
393 $paths = [];
394 foreach ( $ops as $op ) {
395 if ( isset( $op['src'] ) ) {
396 // For things like copy/move/delete with "ignoreMissingSource" and there
397 // is no source file, nothing should happen and there should be no errors.
398 if ( empty( $op['ignoreMissingSource'] )
399 || $this->fileExists( [ 'src' => $op['src'] ] )
400 ) {
401 $paths[] = $op['src'];
402 }
403 }
404 if ( isset( $op['srcs'] ) ) {
405 $paths = array_merge( $paths, $op['srcs'] );
406 }
407 if ( isset( $op['dst'] ) ) {
408 $paths[] = $op['dst'];
409 }
410 }
411
412 return array_values( array_unique( array_filter( $paths, 'FileBackend::isStoragePath' ) ) );
413 }
414
423 protected function substOpBatchPaths( array $ops, FileBackendStore $backend ) {
424 $newOps = []; // operations
425 foreach ( $ops as $op ) {
426 $newOp = $op; // operation
427 foreach ( [ 'src', 'srcs', 'dst', 'dir' ] as $par ) {
428 if ( isset( $newOp[$par] ) ) { // string or array
429 $newOp[$par] = $this->substPaths( $newOp[$par], $backend );
430 }
431 }
432 $newOps[] = $newOp;
433 }
434
435 return $newOps;
436 }
437
445 protected function substOpPaths( array $ops, FileBackendStore $backend ) {
446 $newOps = $this->substOpBatchPaths( [ $ops ], $backend );
447
448 return $newOps[0];
449 }
450
458 protected function substPaths( $paths, FileBackendStore $backend ) {
459 return preg_replace(
460 '!^mwstore://' . preg_quote( $this->name, '!' ) . '/!',
461 StringUtils::escapeRegexReplacement( "mwstore://{$backend->getName()}/" ),
462 $paths // string or array
463 );
464 }
465
472 protected function unsubstPaths( $paths ) {
473 return preg_replace(
474 '!^mwstore://([^/]+)!',
475 StringUtils::escapeRegexReplacement( "mwstore://{$this->name}" ),
476 $paths // string or array
477 );
478 }
479
484 protected function hasVolatileSources( array $ops ) {
485 foreach ( $ops as $op ) {
486 if ( $op['op'] === 'store' && !isset( $op['srcRef'] ) ) {
487 return true; // source file might be deleted anytime after do*Operations()
488 }
489 }
490
491 return false;
492 }
493
494 protected function doQuickOperationsInternal( array $ops ) {
495 $status = $this->newStatus();
496 // Do the operations on the master backend; setting StatusValue fields...
497 $realOps = $this->substOpBatchPaths( $ops, $this->backends[$this->masterIndex] );
498 $masterStatus = $this->backends[$this->masterIndex]->doQuickOperations( $realOps );
499 $status->merge( $masterStatus );
500 // Propagate the operations to the clone backends...
501 foreach ( $this->backends as $index => $backend ) {
502 if ( $index === $this->masterIndex ) {
503 continue; // done already
504 }
505
506 $realOps = $this->substOpBatchPaths( $ops, $backend );
507 if ( $this->asyncWrites && !$this->hasVolatileSources( $ops ) ) {
508 DeferredUpdates::addCallableUpdate(
509 function () use ( $backend, $realOps ) {
510 $backend->doQuickOperations( $realOps );
511 }
512 );
513 } else {
514 $status->merge( $backend->doQuickOperations( $realOps ) );
515 }
516 }
517 // Make 'success', 'successCount', and 'failCount' fields reflect
518 // the overall operation, rather than all the batches for each backend.
519 // Do this by only using success values from the master backend's batch.
520 $status->success = $masterStatus->success;
521 $status->successCount = $masterStatus->successCount;
522 $status->failCount = $masterStatus->failCount;
523
524 return $status;
525 }
526
527 protected function doPrepare( array $params ) {
528 return $this->doDirectoryOp( 'prepare', $params );
529 }
530
531 protected function doSecure( array $params ) {
532 return $this->doDirectoryOp( 'secure', $params );
533 }
534
535 protected function doPublish( array $params ) {
536 return $this->doDirectoryOp( 'publish', $params );
537 }
538
539 protected function doClean( array $params ) {
540 return $this->doDirectoryOp( 'clean', $params );
541 }
542
548 protected function doDirectoryOp( $method, array $params ) {
549 $status = $this->newStatus();
550
551 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
552 $masterStatus = $this->backends[$this->masterIndex]->$method( $realParams );
553 $status->merge( $masterStatus );
554
555 foreach ( $this->backends as $index => $backend ) {
556 if ( $index === $this->masterIndex ) {
557 continue; // already done
558 }
559
560 $realParams = $this->substOpPaths( $params, $backend );
561 if ( $this->asyncWrites ) {
562 DeferredUpdates::addCallableUpdate(
563 function () use ( $backend, $method, $realParams ) {
564 $backend->$method( $realParams );
565 }
566 );
567 } else {
568 $status->merge( $backend->$method( $realParams ) );
569 }
570 }
571
572 return $status;
573 }
574
575 public function concatenate( array $params ) {
576 $status = $this->newStatus();
577 // We are writing to an FS file, so we don't need to do this per-backend
578 $index = $this->getReadIndexFromParams( $params );
579 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
580
581 $status->merge( $this->backends[$index]->concatenate( $realParams ) );
582
583 return $status;
584 }
585
586 public function fileExists( array $params ) {
587 $index = $this->getReadIndexFromParams( $params );
588 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
589
590 return $this->backends[$index]->fileExists( $realParams );
591 }
592
593 public function getFileTimestamp( array $params ) {
594 $index = $this->getReadIndexFromParams( $params );
595 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
596
597 return $this->backends[$index]->getFileTimestamp( $realParams );
598 }
599
600 public function getFileSize( array $params ) {
601 $index = $this->getReadIndexFromParams( $params );
602 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
603
604 return $this->backends[$index]->getFileSize( $realParams );
605 }
606
607 public function getFileStat( array $params ) {
608 $index = $this->getReadIndexFromParams( $params );
609 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
610
611 return $this->backends[$index]->getFileStat( $realParams );
612 }
613
614 public function getFileXAttributes( array $params ) {
615 $index = $this->getReadIndexFromParams( $params );
616 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
617
618 return $this->backends[$index]->getFileXAttributes( $realParams );
619 }
620
621 public function getFileContentsMulti( array $params ) {
622 $index = $this->getReadIndexFromParams( $params );
623 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
624
625 $contentsM = $this->backends[$index]->getFileContentsMulti( $realParams );
626
627 $contents = []; // (path => FSFile) mapping using the proxy backend's name
628 foreach ( $contentsM as $path => $data ) {
629 $contents[$this->unsubstPaths( $path )] = $data;
630 }
631
632 return $contents;
633 }
634
635 public function getFileSha1Base36( array $params ) {
636 $index = $this->getReadIndexFromParams( $params );
637 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
638
639 return $this->backends[$index]->getFileSha1Base36( $realParams );
640 }
641
642 public function getFileProps( array $params ) {
643 $index = $this->getReadIndexFromParams( $params );
644 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
645
646 return $this->backends[$index]->getFileProps( $realParams );
647 }
648
649 public function streamFile( array $params ) {
650 $index = $this->getReadIndexFromParams( $params );
651 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
652
653 return $this->backends[$index]->streamFile( $realParams );
654 }
655
657 $index = $this->getReadIndexFromParams( $params );
658 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
659
660 $fsFilesM = $this->backends[$index]->getLocalReferenceMulti( $realParams );
661
662 $fsFiles = []; // (path => FSFile) mapping using the proxy backend's name
663 foreach ( $fsFilesM as $path => $fsFile ) {
664 $fsFiles[$this->unsubstPaths( $path )] = $fsFile;
665 }
666
667 return $fsFiles;
668 }
669
670 public function getLocalCopyMulti( array $params ) {
671 $index = $this->getReadIndexFromParams( $params );
672 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
673
674 $tempFilesM = $this->backends[$index]->getLocalCopyMulti( $realParams );
675
676 $tempFiles = []; // (path => TempFSFile) mapping using the proxy backend's name
677 foreach ( $tempFilesM as $path => $tempFile ) {
678 $tempFiles[$this->unsubstPaths( $path )] = $tempFile;
679 }
680
681 return $tempFiles;
682 }
683
684 public function getFileHttpUrl( array $params ) {
685 $index = $this->getReadIndexFromParams( $params );
686 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
687
688 return $this->backends[$index]->getFileHttpUrl( $realParams );
689 }
690
691 public function directoryExists( array $params ) {
692 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
693
694 return $this->backends[$this->masterIndex]->directoryExists( $realParams );
695 }
696
697 public function getDirectoryList( array $params ) {
698 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
699
700 return $this->backends[$this->masterIndex]->getDirectoryList( $realParams );
701 }
702
703 public function getFileList( array $params ) {
704 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
705
706 return $this->backends[$this->masterIndex]->getFileList( $realParams );
707 }
708
709 public function getFeatures() {
710 return $this->backends[$this->masterIndex]->getFeatures();
711 }
712
713 public function clearCache( array $paths = null ) {
714 foreach ( $this->backends as $backend ) {
715 $realPaths = is_array( $paths ) ? $this->substPaths( $paths, $backend ) : null;
716 $backend->clearCache( $realPaths );
717 }
718 }
719
720 public function preloadCache( array $paths ) {
721 $realPaths = $this->substPaths( $paths, $this->backends[$this->readIndex] );
722 $this->backends[$this->readIndex]->preloadCache( $realPaths );
723 }
724
725 public function preloadFileStat( array $params ) {
726 $index = $this->getReadIndexFromParams( $params );
727 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
728
729 return $this->backends[$index]->preloadFileStat( $realParams );
730 }
731
733 $realOps = $this->substOpBatchPaths( $ops, $this->backends[$this->masterIndex] );
734 $fileOps = $this->backends[$this->masterIndex]->getOperationsInternal( $realOps );
735 // Get the paths to lock from the master backend
736 $paths = $this->backends[$this->masterIndex]->getPathsToLockForOpsInternal( $fileOps );
737 // Get the paths under the proxy backend's name
738 $pbPaths = [
739 LockManager::LOCK_UW => $this->unsubstPaths( $paths[LockManager::LOCK_UW] ),
740 LockManager::LOCK_EX => $this->unsubstPaths( $paths[LockManager::LOCK_EX] )
741 ];
742
743 // Actually acquire the locks
744 return $this->getScopedFileLocks( $pbPaths, 'mixed', $status );
745 }
746
751 protected function getReadIndexFromParams( array $params ) {
752 return !empty( $params['latest'] ) ? $this->masterIndex : $this->readIndex;
753 }
754}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Proxy backend that mirrors writes to several internal backends.
FileBackendStore[] $backends
Prioritized list of FileBackendStore objects.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getLocalReferenceMulti(array $params)
Like getLocalReference() except it takes an array of storage paths and returns a map of storage paths...
getLocalCopyMulti(array $params)
Like getLocalCopy() except it takes an array of storage paths and returns a map of storage paths to T...
consistencyCheck(array $paths)
Check that a set of files are consistent across all internal backends.
getFileSha1Base36(array $params)
Get a SHA-1 hash of the file at a storage path in the backend.
int $readIndex
Index of read affinity backend.
clearCache(array $paths=null)
Invalidate any in-process file stat and property cache.
getFileStat(array $params)
Get quick information about a file at a storage path in the backend.
getFileContentsMulti(array $params)
Like getFileContents() except it takes an array of storage paths and returns a map of storage paths t...
preloadCache(array $paths)
Preload persistent file stat cache and property cache into in-process cache.
resyncFiles(array $paths, $resyncMode=true)
Check that a set of files are consistent across all internal backends and re-synchronize those files ...
getDirectoryList(array $params)
Get an iterator to list all directories under a storage directory.
__construct(array $config)
Construct a proxy backend that consists of several internal backends.
getFileList(array $params)
Get an iterator to list all stored files under a storage directory.
doOperationsInternal(array $ops, array $opts)
streamFile(array $params)
Stream the file at a storage path in the backend.
int $masterIndex
Index of master backend.
accessibilityCheck(array $paths)
Check that a set of file paths are usable across all internal backends.
getFeatures()
Get the a bitfield of extra features supported by the backend medium.
fileStoragePathsForOps(array $ops)
Get a list of file storage paths to read or write for a list of operations.
concatenate(array $params)
Concatenate a list of storage files into a single file system file.
substOpPaths(array $ops, FileBackendStore $backend)
Same as substOpBatchPaths() but for a single operation.
substOpBatchPaths(array $ops, FileBackendStore $backend)
Substitute the backend name in storage path parameters for a set of operations with that of a given i...
getFileProps(array $params)
Get the properties of the file at a storage path in the backend.
doDirectoryOp( $method, array $params)
getScopedLocksForOps(array $ops, StatusValue $status)
Get an array of scoped locks needed for a batch of file operations.
getFileHttpUrl(array $params)
Return an HTTP URL to a given file that requires no authentication to use.
preloadFileStat(array $params)
Preload file stat information (concurrently if possible) into in-process cache.
getFileSize(array $params)
Get the size (bytes) of a file at a storage path in the backend.
getFileXAttributes(array $params)
Get metadata about a file at a storage path in the backend.
substPaths( $paths, FileBackendStore $backend)
Substitute the backend of storage paths with an internal backend's name.
directoryExists(array $params)
Check if a directory exists at a given storage path.
getFileTimestamp(array $params)
Get the last-modified timestamp of the file at a storage path.
unsubstPaths( $paths)
Substitute the backend of internal storage paths with the proxy backend's name.
Base class for all backends using particular storage medium.
Base class for all file backend classes (including multi-write backends).
string $name
Unique backend name.
string $domainId
Unique domain name.
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
newStatus()
Yields the result of the status wrapper callback on either:
FileJournal $fileJournal
Generic operation result class Has warning/error list, boolean status and arbitrary value.
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1305
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2055
and how to run hooks for an and one after Each event has a name
Definition hooks.txt:12
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$params