MediaWiki  1.28.0
FileOp.php
Go to the documentation of this file.
1 <?php
25 
37 abstract class FileOp {
39  protected $params = [];
40 
42  protected $backend;
44  protected $logger;
45 
47  protected $state = self::STATE_NEW;
48 
50  protected $failed = false;
51 
53  protected $async = false;
54 
56  protected $batchId;
57 
59  protected $doOperation = true;
60 
62  protected $sourceSha1;
63 
65  protected $overwriteSameCase;
66 
68  protected $destExists;
69 
70  /* Object life-cycle */
71  const STATE_NEW = 1;
72  const STATE_CHECKED = 2;
73  const STATE_ATTEMPTED = 3;
74 
83  final public function __construct(
85  ) {
86  $this->backend = $backend;
87  $this->logger = $logger;
88  list( $required, $optional, $paths ) = $this->allowedParams();
89  foreach ( $required as $name ) {
90  if ( isset( $params[$name] ) ) {
91  $this->params[$name] = $params[$name];
92  } else {
93  throw new InvalidArgumentException( "File operation missing parameter '$name'." );
94  }
95  }
96  foreach ( $optional as $name ) {
97  if ( isset( $params[$name] ) ) {
98  $this->params[$name] = $params[$name];
99  }
100  }
101  foreach ( $paths as $name ) {
102  if ( isset( $this->params[$name] ) ) {
103  // Normalize paths so the paths to the same file have the same string
104  $this->params[$name] = self::normalizeIfValidStoragePath( $this->params[$name] );
105  }
106  }
107  }
108 
115  protected static function normalizeIfValidStoragePath( $path ) {
118 
119  return ( $res !== null ) ? $res : $path;
120  }
121 
122  return $path;
123  }
124 
130  final public function setBatchId( $batchId ) {
131  $this->batchId = $batchId;
132  }
133 
140  final public function getParam( $name ) {
141  return isset( $this->params[$name] ) ? $this->params[$name] : null;
142  }
143 
149  final public function failed() {
150  return $this->failed;
151  }
152 
158  final public static function newPredicates() {
159  return [ 'exists' => [], 'sha1' => [] ];
160  }
161 
167  final public static function newDependencies() {
168  return [ 'read' => [], 'write' => [] ];
169  }
170 
177  final public function applyDependencies( array $deps ) {
178  $deps['read'] += array_fill_keys( $this->storagePathsRead(), 1 );
179  $deps['write'] += array_fill_keys( $this->storagePathsChanged(), 1 );
180 
181  return $deps;
182  }
183 
190  final public function dependsOn( array $deps ) {
191  foreach ( $this->storagePathsChanged() as $path ) {
192  if ( isset( $deps['read'][$path] ) || isset( $deps['write'][$path] ) ) {
193  return true; // "output" or "anti" dependency
194  }
195  }
196  foreach ( $this->storagePathsRead() as $path ) {
197  if ( isset( $deps['write'][$path] ) ) {
198  return true; // "flow" dependency
199  }
200  }
201 
202  return false;
203  }
204 
212  final public function getJournalEntries( array $oPredicates, array $nPredicates ) {
213  if ( !$this->doOperation ) {
214  return []; // this is a no-op
215  }
216  $nullEntries = [];
217  $updateEntries = [];
218  $deleteEntries = [];
219  $pathsUsed = array_merge( $this->storagePathsRead(), $this->storagePathsChanged() );
220  foreach ( array_unique( $pathsUsed ) as $path ) {
221  $nullEntries[] = [ // assertion for recovery
222  'op' => 'null',
223  'path' => $path,
224  'newSha1' => $this->fileSha1( $path, $oPredicates )
225  ];
226  }
227  foreach ( $this->storagePathsChanged() as $path ) {
228  if ( $nPredicates['sha1'][$path] === false ) { // deleted
229  $deleteEntries[] = [
230  'op' => 'delete',
231  'path' => $path,
232  'newSha1' => ''
233  ];
234  } else { // created/updated
235  $updateEntries[] = [
236  'op' => $this->fileExists( $path, $oPredicates ) ? 'update' : 'create',
237  'path' => $path,
238  'newSha1' => $nPredicates['sha1'][$path]
239  ];
240  }
241  }
242 
243  return array_merge( $nullEntries, $updateEntries, $deleteEntries );
244  }
245 
254  final public function precheck( array &$predicates ) {
255  if ( $this->state !== self::STATE_NEW ) {
256  return StatusValue::newFatal( 'fileop-fail-state', self::STATE_NEW, $this->state );
257  }
258  $this->state = self::STATE_CHECKED;
259  $status = $this->doPrecheck( $predicates );
260  if ( !$status->isOK() ) {
261  $this->failed = true;
262  }
263 
264  return $status;
265  }
266 
271  protected function doPrecheck( array &$predicates ) {
272  return StatusValue::newGood();
273  }
274 
280  final public function attempt() {
281  if ( $this->state !== self::STATE_CHECKED ) {
282  return StatusValue::newFatal( 'fileop-fail-state', self::STATE_CHECKED, $this->state );
283  } elseif ( $this->failed ) { // failed precheck
284  return StatusValue::newFatal( 'fileop-fail-attempt-precheck' );
285  }
286  $this->state = self::STATE_ATTEMPTED;
287  if ( $this->doOperation ) {
288  $status = $this->doAttempt();
289  if ( !$status->isOK() ) {
290  $this->failed = true;
291  $this->logFailure( 'attempt' );
292  }
293  } else { // no-op
295  }
296 
297  return $status;
298  }
299 
303  protected function doAttempt() {
304  return StatusValue::newGood();
305  }
306 
312  final public function attemptAsync() {
313  $this->async = true;
314  $result = $this->attempt();
315  $this->async = false;
316 
317  return $result;
318  }
319 
325  protected function allowedParams() {
326  return [ [], [], [] ];
327  }
328 
335  protected function setFlags( array $params ) {
336  return [ 'async' => $this->async ] + $params;
337  }
338 
344  public function storagePathsRead() {
345  return [];
346  }
347 
353  public function storagePathsChanged() {
354  return [];
355  }
356 
365  protected function precheckDestExistence( array $predicates ) {
367  // Get hash of source file/string and the destination file
368  $this->sourceSha1 = $this->getSourceSha1Base36(); // FS file or data string
369  if ( $this->sourceSha1 === null ) { // file in storage?
370  $this->sourceSha1 = $this->fileSha1( $this->params['src'], $predicates );
371  }
372  $this->overwriteSameCase = false;
373  $this->destExists = $this->fileExists( $this->params['dst'], $predicates );
374  if ( $this->destExists ) {
375  if ( $this->getParam( 'overwrite' ) ) {
376  return $status; // OK
377  } elseif ( $this->getParam( 'overwriteSame' ) ) {
378  $dhash = $this->fileSha1( $this->params['dst'], $predicates );
379  // Check if hashes are valid and match each other...
380  if ( !strlen( $this->sourceSha1 ) || !strlen( $dhash ) ) {
381  $status->fatal( 'backend-fail-hashes' );
382  } elseif ( $this->sourceSha1 !== $dhash ) {
383  // Give an error if the files are not identical
384  $status->fatal( 'backend-fail-notsame', $this->params['dst'] );
385  } else {
386  $this->overwriteSameCase = true; // OK
387  }
388 
389  return $status; // do nothing; either OK or bad status
390  } else {
391  $status->fatal( 'backend-fail-alreadyexists', $this->params['dst'] );
392 
393  return $status;
394  }
395  }
396 
397  return $status;
398  }
399 
406  protected function getSourceSha1Base36() {
407  return null; // N/A
408  }
409 
417  final protected function fileExists( $source, array $predicates ) {
418  if ( isset( $predicates['exists'][$source] ) ) {
419  return $predicates['exists'][$source]; // previous op assures this
420  } else {
421  $params = [ 'src' => $source, 'latest' => true ];
422 
423  return $this->backend->fileExists( $params );
424  }
425  }
426 
434  final protected function fileSha1( $source, array $predicates ) {
435  if ( isset( $predicates['sha1'][$source] ) ) {
436  return $predicates['sha1'][$source]; // previous op assures this
437  } elseif ( isset( $predicates['exists'][$source] ) && !$predicates['exists'][$source] ) {
438  return false; // previous op assures this
439  } else {
440  $params = [ 'src' => $source, 'latest' => true ];
441 
442  return $this->backend->getFileSha1Base36( $params );
443  }
444  }
445 
451  public function getBackend() {
452  return $this->backend;
453  }
454 
460  final public function logFailure( $action ) {
462  $params['failedAction'] = $action;
463  try {
464  $this->logger->error( get_class( $this ) .
465  " failed (batch #{$this->batchId}): " . FormatJson::encode( $params ) );
466  } catch ( Exception $e ) {
467  // bad config? debug log error?
468  }
469  }
470 }
setBatchId($batchId)
Set the batch UUID this operation belongs to.
Definition: FileOp.php:130
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
the array() calling protocol came about after MediaWiki 1.4rc1.
logFailure($action)
Log a file operation failure and preserve any temp files.
Definition: FileOp.php:460
getJournalEntries(array $oPredicates, array $nPredicates)
Get the file journal entries for this file operation.
Definition: FileOp.php:212
bool $failed
Definition: FileOp.php:50
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:2102
FileBackend helper class for representing operations.
Definition: FileOp.php:37
static newFatal($message)
Factory function for fatal errors.
Definition: StatusValue.php:63
applyDependencies(array $deps)
Update a dependency tracking array to account for this operation.
Definition: FileOp.php:177
fileSha1($source, array $predicates)
Get the SHA-1 of a file in storage when this operation is attempted.
Definition: FileOp.php:434
getParam($name)
Get the value of the parameter with the given name.
Definition: FileOp.php:140
array $params
Definition: FileOp.php:39
$source
setFlags(array $params)
Adjust params to FileBackendStore internal file calls.
Definition: FileOp.php:335
bool $doOperation
Operation is not a no-op.
Definition: FileOp.php:59
string $batchId
Definition: FileOp.php:56
const STATE_CHECKED
Definition: FileOp.php:72
const STATE_NEW
Definition: FileOp.php:71
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1934
attempt()
Attempt the operation.
Definition: FileOp.php:280
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:1936
int $state
Definition: FileOp.php:47
const STATE_ATTEMPTED
Definition: FileOp.php:73
storagePathsRead()
Get a list of storage paths read from for this operation.
Definition: FileOp.php:344
dependsOn(array $deps)
Check if this operation changes files listed in $paths.
Definition: FileOp.php:190
static newPredicates()
Get a new empty predicates array for precheck()
Definition: FileOp.php:158
precheckDestExistence(array $predicates)
Check for errors with regards to the destination file already existing.
Definition: FileOp.php:365
$res
Definition: database.txt:21
static isStoragePath($path)
Check if a given path is a "mwstore://" path.
attemptAsync()
Attempt the operation in the background.
Definition: FileOp.php:312
getSourceSha1Base36()
precheckDestExistence() helper function to get the source file SHA-1.
Definition: FileOp.php:406
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
allowedParams()
Get the file operation parameters.
Definition: FileOp.php:325
static newGood($value=null)
Factory function for good results.
Definition: StatusValue.php:76
getBackend()
Get the backend this operation is for.
Definition: FileOp.php:451
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
Definition: distributors.txt:9
doAttempt()
Definition: FileOp.php:303
static normalizeIfValidStoragePath($path)
Normalize a string if it is a valid storage path.
Definition: FileOp.php:115
Base class for all backends using particular storage medium.
precheck(array &$predicates)
Check preconditions of the operation without writing anything.
Definition: FileOp.php:254
FileBackendStore $backend
Definition: FileOp.php:42
doPrecheck(array &$predicates)
Definition: FileOp.php:271
static normalizeStoragePath($storagePath)
Normalize a storage path by cleaning up directory separators.
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:35
bool $destExists
Definition: FileOp.php:68
static newDependencies()
Get a new empty dependency tracking array for paths read/written to.
Definition: FileOp.php:167
storagePathsChanged()
Get a list of storage paths written to for this operation.
Definition: FileOp.php:353
fileExists($source, array $predicates)
Check if a file will exist in storage when this operation is attempted.
Definition: FileOp.php:417
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1046
__construct(FileBackendStore $backend, array $params, LoggerInterface $logger)
Build a new batch file operation transaction.
Definition: FileOp.php:83
LoggerInterface $logger
Definition: FileOp.php:44
bool $async
Definition: FileOp.php:53
string $sourceSha1
Definition: FileOp.php:62
failed()
Check if this operation failed precheck() or attempt()
Definition: FileOp.php:149
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300
bool $overwriteSameCase
Definition: FileOp.php:65