Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / filerepo / backend / FileOp.php
blobd9fbafd9b155a36f8d66159c059d5d5b6746109b
1 <?php
2 /**
3 * Helper class for representing operations with transaction support.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
25 /**
26 * FileBackend helper class for representing operations.
27 * Do not use this class from places outside FileBackend.
29 * Methods called from FileOpBatch::attempt() should avoid throwing
30 * exceptions at all costs. FileOp objects should be lightweight in order
31 * to support large arrays in memory and serialization.
33 * @ingroup FileBackend
34 * @since 1.19
36 abstract class FileOp {
37 /** @var Array */
38 protected $params = array();
39 /** @var FileBackendStore */
40 protected $backend;
42 protected $state = self::STATE_NEW; // integer
43 protected $failed = false; // boolean
44 protected $async = false; // boolean
45 protected $useLatest = true; // boolean
46 protected $batchId; // string
48 protected $sourceSha1; // string
49 protected $destSameAsSource; // boolean
51 /* Object life-cycle */
52 const STATE_NEW = 1;
53 const STATE_CHECKED = 2;
54 const STATE_ATTEMPTED = 3;
56 /**
57 * Build a new file operation transaction
59 * @param $backend FileBackendStore
60 * @param $params Array
61 * @throws MWException
63 final public function __construct( FileBackendStore $backend, array $params ) {
64 $this->backend = $backend;
65 list( $required, $optional ) = $this->allowedParams();
66 foreach ( $required as $name ) {
67 if ( isset( $params[$name] ) ) {
68 $this->params[$name] = $params[$name];
69 } else {
70 throw new MWException( "File operation missing parameter '$name'." );
73 foreach ( $optional as $name ) {
74 if ( isset( $params[$name] ) ) {
75 $this->params[$name] = $params[$name];
78 $this->params = $params;
81 /**
82 * Set the batch UUID this operation belongs to
84 * @param $batchId string
85 * @return void
87 final public function setBatchId( $batchId ) {
88 $this->batchId = $batchId;
91 /**
92 * Whether to allow stale data for file reads and stat checks
94 * @param $allowStale bool
95 * @return void
97 final public function allowStaleReads( $allowStale ) {
98 $this->useLatest = !$allowStale;
102 * Get the value of the parameter with the given name
104 * @param $name string
105 * @return mixed Returns null if the parameter is not set
107 final public function getParam( $name ) {
108 return isset( $this->params[$name] ) ? $this->params[$name] : null;
112 * Check if this operation failed precheck() or attempt()
114 * @return bool
116 final public function failed() {
117 return $this->failed;
121 * Get a new empty predicates array for precheck()
123 * @return Array
125 final public static function newPredicates() {
126 return array( 'exists' => array(), 'sha1' => array() );
130 * Get a new empty dependency tracking array for paths read/written to
132 * @return Array
134 final public static function newDependencies() {
135 return array( 'read' => array(), 'write' => array() );
139 * Update a dependency tracking array to account for this operation
141 * @param $deps Array Prior path reads/writes; format of FileOp::newPredicates()
142 * @return Array
144 final public function applyDependencies( array $deps ) {
145 $deps['read'] += array_fill_keys( $this->storagePathsRead(), 1 );
146 $deps['write'] += array_fill_keys( $this->storagePathsChanged(), 1 );
147 return $deps;
151 * Check if this operation changes files listed in $paths
153 * @param $paths Array Prior path reads/writes; format of FileOp::newPredicates()
154 * @return boolean
156 final public function dependsOn( array $deps ) {
157 foreach ( $this->storagePathsChanged() as $path ) {
158 if ( isset( $deps['read'][$path] ) || isset( $deps['write'][$path] ) ) {
159 return true; // "output" or "anti" dependency
162 foreach ( $this->storagePathsRead() as $path ) {
163 if ( isset( $deps['write'][$path] ) ) {
164 return true; // "flow" dependency
167 return false;
171 * Get the file journal entries for this file operation
173 * @param $oPredicates Array Pre-op info about files (format of FileOp::newPredicates)
174 * @param $nPredicates Array Post-op info about files (format of FileOp::newPredicates)
175 * @return Array
177 final public function getJournalEntries( array $oPredicates, array $nPredicates ) {
178 $nullEntries = array();
179 $updateEntries = array();
180 $deleteEntries = array();
181 $pathsUsed = array_merge( $this->storagePathsRead(), $this->storagePathsChanged() );
182 foreach ( $pathsUsed as $path ) {
183 $nullEntries[] = array( // assertion for recovery
184 'op' => 'null',
185 'path' => $path,
186 'newSha1' => $this->fileSha1( $path, $oPredicates )
189 foreach ( $this->storagePathsChanged() as $path ) {
190 if ( $nPredicates['sha1'][$path] === false ) { // deleted
191 $deleteEntries[] = array(
192 'op' => 'delete',
193 'path' => $path,
194 'newSha1' => ''
196 } else { // created/updated
197 $updateEntries[] = array(
198 'op' => $this->fileExists( $path, $oPredicates ) ? 'update' : 'create',
199 'path' => $path,
200 'newSha1' => $nPredicates['sha1'][$path]
204 return array_merge( $nullEntries, $updateEntries, $deleteEntries );
208 * Check preconditions of the operation without writing anything
210 * @param $predicates Array
211 * @return Status
213 final public function precheck( array &$predicates ) {
214 if ( $this->state !== self::STATE_NEW ) {
215 return Status::newFatal( 'fileop-fail-state', self::STATE_NEW, $this->state );
217 $this->state = self::STATE_CHECKED;
218 $status = $this->doPrecheck( $predicates );
219 if ( !$status->isOK() ) {
220 $this->failed = true;
222 return $status;
226 * @return Status
228 protected function doPrecheck( array &$predicates ) {
229 return Status::newGood();
233 * Attempt the operation
235 * @return Status
237 final public function attempt() {
238 if ( $this->state !== self::STATE_CHECKED ) {
239 return Status::newFatal( 'fileop-fail-state', self::STATE_CHECKED, $this->state );
240 } elseif ( $this->failed ) { // failed precheck
241 return Status::newFatal( 'fileop-fail-attempt-precheck' );
243 $this->state = self::STATE_ATTEMPTED;
244 $status = $this->doAttempt();
245 if ( !$status->isOK() ) {
246 $this->failed = true;
247 $this->logFailure( 'attempt' );
249 return $status;
253 * @return Status
255 protected function doAttempt() {
256 return Status::newGood();
260 * Attempt the operation in the background
262 * @return Status
264 final public function attemptAsync() {
265 $this->async = true;
266 $result = $this->attempt();
267 $this->async = false;
268 return $result;
272 * Get the file operation parameters
274 * @return Array (required params list, optional params list)
276 protected function allowedParams() {
277 return array( array(), array() );
281 * Adjust params to FileBackendStore internal file calls
283 * @param $params Array
284 * @return Array (required params list, optional params list)
286 protected function setFlags( array $params ) {
287 return array( 'async' => $this->async ) + $params;
291 * Get a list of storage paths read from for this operation
293 * @return Array
295 final public function storagePathsRead() {
296 return array_map( 'FileBackend::normalizeStoragePath', $this->doStoragePathsRead() );
300 * @see FileOp::storagePathsRead()
301 * @return Array
303 protected function doStoragePathsRead() {
304 return array();
308 * Get a list of storage paths written to for this operation
310 * @return Array
312 final public function storagePathsChanged() {
313 return array_map( 'FileBackend::normalizeStoragePath', $this->doStoragePathsChanged() );
317 * @see FileOp::storagePathsChanged()
318 * @return Array
320 protected function doStoragePathsChanged() {
321 return array();
325 * Check for errors with regards to the destination file already existing.
326 * This also updates the destSameAsSource and sourceSha1 member variables.
327 * A bad status will be returned if there is no chance it can be overwritten.
329 * @param $predicates Array
330 * @return Status
332 protected function precheckDestExistence( array $predicates ) {
333 $status = Status::newGood();
334 // Get hash of source file/string and the destination file
335 $this->sourceSha1 = $this->getSourceSha1Base36(); // FS file or data string
336 if ( $this->sourceSha1 === null ) { // file in storage?
337 $this->sourceSha1 = $this->fileSha1( $this->params['src'], $predicates );
339 $this->destSameAsSource = false;
340 if ( $this->fileExists( $this->params['dst'], $predicates ) ) {
341 if ( $this->getParam( 'overwrite' ) ) {
342 return $status; // OK
343 } elseif ( $this->getParam( 'overwriteSame' ) ) {
344 $dhash = $this->fileSha1( $this->params['dst'], $predicates );
345 // Check if hashes are valid and match each other...
346 if ( !strlen( $this->sourceSha1 ) || !strlen( $dhash ) ) {
347 $status->fatal( 'backend-fail-hashes' );
348 } elseif ( $this->sourceSha1 !== $dhash ) {
349 // Give an error if the files are not identical
350 $status->fatal( 'backend-fail-notsame', $this->params['dst'] );
351 } else {
352 $this->destSameAsSource = true; // OK
354 return $status; // do nothing; either OK or bad status
355 } else {
356 $status->fatal( 'backend-fail-alreadyexists', $this->params['dst'] );
357 return $status;
360 return $status;
364 * precheckDestExistence() helper function to get the source file SHA-1.
365 * Subclasses should overwride this iff the source is not in storage.
367 * @return string|bool Returns false on failure
369 protected function getSourceSha1Base36() {
370 return null; // N/A
374 * Check if a file will exist in storage when this operation is attempted
376 * @param $source string Storage path
377 * @param $predicates Array
378 * @return bool
380 final protected function fileExists( $source, array $predicates ) {
381 if ( isset( $predicates['exists'][$source] ) ) {
382 return $predicates['exists'][$source]; // previous op assures this
383 } else {
384 $params = array( 'src' => $source, 'latest' => $this->useLatest );
385 return $this->backend->fileExists( $params );
390 * Get the SHA-1 of a file in storage when this operation is attempted
392 * @param $source string Storage path
393 * @param $predicates Array
394 * @return string|bool False on failure
396 final protected function fileSha1( $source, array $predicates ) {
397 if ( isset( $predicates['sha1'][$source] ) ) {
398 return $predicates['sha1'][$source]; // previous op assures this
399 } else {
400 $params = array( 'src' => $source, 'latest' => $this->useLatest );
401 return $this->backend->getFileSha1Base36( $params );
406 * Get the backend this operation is for
408 * @return FileBackendStore
410 public function getBackend() {
411 return $this->backend;
415 * Log a file operation failure and preserve any temp files
417 * @param $action string
418 * @return void
420 final public function logFailure( $action ) {
421 $params = $this->params;
422 $params['failedAction'] = $action;
423 try {
424 wfDebugLog( 'FileOperation', get_class( $this ) .
425 " failed (batch #{$this->batchId}): " . FormatJson::encode( $params ) );
426 } catch ( Exception $e ) {
427 // bad config? debug log error?
433 * Store a file into the backend from a file on the file system.
434 * Parameters similar to FileBackendStore::storeInternal(), which include:
435 * src : source path on file system
436 * dst : destination storage path
437 * overwrite : do nothing and pass if an identical file exists at destination
438 * overwriteSame : override any existing file at destination
440 class StoreFileOp extends FileOp {
443 * @return array
445 protected function allowedParams() {
446 return array( array( 'src', 'dst' ), array( 'overwrite', 'overwriteSame' ) );
450 * @param $predicates array
451 * @return Status
453 protected function doPrecheck( array &$predicates ) {
454 $status = Status::newGood();
455 // Check if the source file exists on the file system
456 if ( !is_file( $this->params['src'] ) ) {
457 $status->fatal( 'backend-fail-notexists', $this->params['src'] );
458 return $status;
459 // Check if the source file is too big
460 } elseif ( filesize( $this->params['src'] ) > $this->backend->maxFileSizeInternal() ) {
461 $status->fatal( 'backend-fail-maxsize',
462 $this->params['dst'], $this->backend->maxFileSizeInternal() );
463 $status->fatal( 'backend-fail-store', $this->params['src'], $this->params['dst'] );
464 return $status;
465 // Check if a file can be placed at the destination
466 } elseif ( !$this->backend->isPathUsableInternal( $this->params['dst'] ) ) {
467 $status->fatal( 'backend-fail-usable', $this->params['dst'] );
468 $status->fatal( 'backend-fail-store', $this->params['src'], $this->params['dst'] );
469 return $status;
471 // Check if destination file exists
472 $status->merge( $this->precheckDestExistence( $predicates ) );
473 if ( $status->isOK() ) {
474 // Update file existence predicates
475 $predicates['exists'][$this->params['dst']] = true;
476 $predicates['sha1'][$this->params['dst']] = $this->sourceSha1;
478 return $status; // safe to call attempt()
482 * @return Status
484 protected function doAttempt() {
485 // Store the file at the destination
486 if ( !$this->destSameAsSource ) {
487 return $this->backend->storeInternal( $this->setFlags( $this->params ) );
489 return Status::newGood();
493 * @return bool|string
495 protected function getSourceSha1Base36() {
496 wfSuppressWarnings();
497 $hash = sha1_file( $this->params['src'] );
498 wfRestoreWarnings();
499 if ( $hash !== false ) {
500 $hash = wfBaseConvert( $hash, 16, 36, 31 );
502 return $hash;
505 protected function doStoragePathsChanged() {
506 return array( $this->params['dst'] );
511 * Create a file in the backend with the given content.
512 * Parameters similar to FileBackendStore::createInternal(), which include:
513 * content : the raw file contents
514 * dst : destination storage path
515 * overwrite : do nothing and pass if an identical file exists at destination
516 * overwriteSame : override any existing file at destination
518 class CreateFileOp extends FileOp {
519 protected function allowedParams() {
520 return array( array( 'content', 'dst' ), array( 'overwrite', 'overwriteSame' ) );
523 protected function doPrecheck( array &$predicates ) {
524 $status = Status::newGood();
525 // Check if the source data is too big
526 if ( strlen( $this->getParam( 'content' ) ) > $this->backend->maxFileSizeInternal() ) {
527 $status->fatal( 'backend-fail-maxsize',
528 $this->params['dst'], $this->backend->maxFileSizeInternal() );
529 $status->fatal( 'backend-fail-create', $this->params['dst'] );
530 return $status;
531 // Check if a file can be placed at the destination
532 } elseif ( !$this->backend->isPathUsableInternal( $this->params['dst'] ) ) {
533 $status->fatal( 'backend-fail-usable', $this->params['dst'] );
534 $status->fatal( 'backend-fail-create', $this->params['dst'] );
535 return $status;
537 // Check if destination file exists
538 $status->merge( $this->precheckDestExistence( $predicates ) );
539 if ( $status->isOK() ) {
540 // Update file existence predicates
541 $predicates['exists'][$this->params['dst']] = true;
542 $predicates['sha1'][$this->params['dst']] = $this->sourceSha1;
544 return $status; // safe to call attempt()
548 * @return Status
550 protected function doAttempt() {
551 if ( !$this->destSameAsSource ) {
552 // Create the file at the destination
553 return $this->backend->createInternal( $this->setFlags( $this->params ) );
555 return Status::newGood();
559 * @return bool|String
561 protected function getSourceSha1Base36() {
562 return wfBaseConvert( sha1( $this->params['content'] ), 16, 36, 31 );
566 * @return array
568 protected function doStoragePathsChanged() {
569 return array( $this->params['dst'] );
574 * Copy a file from one storage path to another in the backend.
575 * Parameters similar to FileBackendStore::copyInternal(), which include:
576 * src : source storage path
577 * dst : destination storage path
578 * overwrite : do nothing and pass if an identical file exists at destination
579 * overwriteSame : override any existing file at destination
581 class CopyFileOp extends FileOp {
584 * @return array
586 protected function allowedParams() {
587 return array( array( 'src', 'dst' ), array( 'overwrite', 'overwriteSame' ) );
591 * @param $predicates array
592 * @return Status
594 protected function doPrecheck( array &$predicates ) {
595 $status = Status::newGood();
596 // Check if the source file exists
597 if ( !$this->fileExists( $this->params['src'], $predicates ) ) {
598 $status->fatal( 'backend-fail-notexists', $this->params['src'] );
599 return $status;
600 // Check if a file can be placed at the destination
601 } elseif ( !$this->backend->isPathUsableInternal( $this->params['dst'] ) ) {
602 $status->fatal( 'backend-fail-usable', $this->params['dst'] );
603 $status->fatal( 'backend-fail-copy', $this->params['src'], $this->params['dst'] );
604 return $status;
606 // Check if destination file exists
607 $status->merge( $this->precheckDestExistence( $predicates ) );
608 if ( $status->isOK() ) {
609 // Update file existence predicates
610 $predicates['exists'][$this->params['dst']] = true;
611 $predicates['sha1'][$this->params['dst']] = $this->sourceSha1;
613 return $status; // safe to call attempt()
617 * @return Status
619 protected function doAttempt() {
620 // Do nothing if the src/dst paths are the same
621 if ( $this->params['src'] !== $this->params['dst'] ) {
622 // Copy the file into the destination
623 if ( !$this->destSameAsSource ) {
624 return $this->backend->copyInternal( $this->setFlags( $this->params ) );
627 return Status::newGood();
631 * @return array
633 protected function doStoragePathsRead() {
634 return array( $this->params['src'] );
638 * @return array
640 protected function doStoragePathsChanged() {
641 return array( $this->params['dst'] );
646 * Move a file from one storage path to another in the backend.
647 * Parameters similar to FileBackendStore::moveInternal(), which include:
648 * src : source storage path
649 * dst : destination storage path
650 * overwrite : do nothing and pass if an identical file exists at destination
651 * overwriteSame : override any existing file at destination
653 class MoveFileOp extends FileOp {
655 * @return array
657 protected function allowedParams() {
658 return array( array( 'src', 'dst' ), array( 'overwrite', 'overwriteSame' ) );
662 * @param $predicates array
663 * @return Status
665 protected function doPrecheck( array &$predicates ) {
666 $status = Status::newGood();
667 // Check if the source file exists
668 if ( !$this->fileExists( $this->params['src'], $predicates ) ) {
669 $status->fatal( 'backend-fail-notexists', $this->params['src'] );
670 return $status;
671 // Check if a file can be placed at the destination
672 } elseif ( !$this->backend->isPathUsableInternal( $this->params['dst'] ) ) {
673 $status->fatal( 'backend-fail-usable', $this->params['dst'] );
674 $status->fatal( 'backend-fail-move', $this->params['src'], $this->params['dst'] );
675 return $status;
677 // Check if destination file exists
678 $status->merge( $this->precheckDestExistence( $predicates ) );
679 if ( $status->isOK() ) {
680 // Update file existence predicates
681 $predicates['exists'][$this->params['src']] = false;
682 $predicates['sha1'][$this->params['src']] = false;
683 $predicates['exists'][$this->params['dst']] = true;
684 $predicates['sha1'][$this->params['dst']] = $this->sourceSha1;
686 return $status; // safe to call attempt()
690 * @return Status
692 protected function doAttempt() {
693 // Do nothing if the src/dst paths are the same
694 if ( $this->params['src'] !== $this->params['dst'] ) {
695 if ( !$this->destSameAsSource ) {
696 // Move the file into the destination
697 return $this->backend->moveInternal( $this->setFlags( $this->params ) );
698 } else {
699 // Just delete source as the destination needs no changes
700 $params = array( 'src' => $this->params['src'] );
701 return $this->backend->deleteInternal( $this->setFlags( $params ) );
704 return Status::newGood();
708 * @return array
710 protected function doStoragePathsRead() {
711 return array( $this->params['src'] );
715 * @return array
717 protected function doStoragePathsChanged() {
718 return array( $this->params['src'], $this->params['dst'] );
723 * Delete a file at the given storage path from the backend.
724 * Parameters similar to FileBackendStore::deleteInternal(), which include:
725 * src : source storage path
726 * ignoreMissingSource : don't return an error if the file does not exist
728 class DeleteFileOp extends FileOp {
730 * @return array
732 protected function allowedParams() {
733 return array( array( 'src' ), array( 'ignoreMissingSource' ) );
736 protected $needsDelete = true;
739 * @param array $predicates
740 * @return Status
742 protected function doPrecheck( array &$predicates ) {
743 $status = Status::newGood();
744 // Check if the source file exists
745 if ( !$this->fileExists( $this->params['src'], $predicates ) ) {
746 if ( !$this->getParam( 'ignoreMissingSource' ) ) {
747 $status->fatal( 'backend-fail-notexists', $this->params['src'] );
748 return $status;
750 $this->needsDelete = false;
752 // Update file existence predicates
753 $predicates['exists'][$this->params['src']] = false;
754 $predicates['sha1'][$this->params['src']] = false;
755 return $status; // safe to call attempt()
759 * @return Status
761 protected function doAttempt() {
762 if ( $this->needsDelete ) {
763 // Delete the source file
764 return $this->backend->deleteInternal( $this->setFlags( $this->params ) );
766 return Status::newGood();
770 * @return array
772 protected function doStoragePathsChanged() {
773 return array( $this->params['src'] );
778 * Placeholder operation that has no params and does nothing
780 class NullFileOp extends FileOp {}