MediaWiki  master
LocalFileRestoreBatch.php
Go to the documentation of this file.
1 <?php
25 
32  private $file;
33 
35  private $cleanupBatch;
36 
38  private $ids;
39 
41  private $all;
42 
44  private $unsuppress = false;
45 
50  function __construct( File $file, $unsuppress = false ) {
51  $this->file = $file;
52  $this->cleanupBatch = [];
53  $this->ids = [];
54  $this->unsuppress = $unsuppress;
55  }
56 
61  public function addId( $fa_id ) {
62  $this->ids[] = $fa_id;
63  }
64 
69  public function addIds( $ids ) {
70  $this->ids = array_merge( $this->ids, $ids );
71  }
72 
76  public function addAll() {
77  $this->all = true;
78  }
79 
88  public function execute() {
90  global $wgLang;
91 
92  $repo = $this->file->getRepo();
93  if ( !$this->all && !$this->ids ) {
94  // Do nothing
95  return $repo->newGood();
96  }
97 
98  $lockOwnsTrx = $this->file->lock();
99 
100  $dbw = $this->file->repo->getMasterDB();
101 
102  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
103  $actorMigration = ActorMigration::newMigration();
104 
105  $status = $this->file->repo->newGood();
106 
107  $exists = (bool)$dbw->selectField( 'image', '1',
108  [ 'img_name' => $this->file->getName() ],
109  __METHOD__,
110  // The lock() should already prevents changes, but this still may need
111  // to bypass any transaction snapshot. However, if lock() started the
112  // trx (which it probably did) then snapshot is post-lock and up-to-date.
113  $lockOwnsTrx ? [] : [ 'LOCK IN SHARE MODE' ]
114  );
115 
116  // Fetch all or selected archived revisions for the file,
117  // sorted from the most recent to the oldest.
118  $conditions = [ 'fa_name' => $this->file->getName() ];
119 
120  if ( !$this->all ) {
121  $conditions['fa_id'] = $this->ids;
122  }
123 
124  $arFileQuery = ArchivedFile::getQueryInfo();
125  $result = $dbw->select(
126  $arFileQuery['tables'],
127  $arFileQuery['fields'],
128  $conditions,
129  __METHOD__,
130  [ 'ORDER BY' => 'fa_timestamp DESC' ],
131  $arFileQuery['joins']
132  );
133 
134  $idsPresent = [];
135  $storeBatch = [];
136  $insertBatch = [];
137  $insertCurrent = false;
138  $deleteIds = [];
139  $first = true;
140  $archiveNames = [];
141 
142  foreach ( $result as $row ) {
143  $idsPresent[] = $row->fa_id;
144 
145  if ( $row->fa_name != $this->file->getName() ) {
146  $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
147  $status->failCount++;
148  continue;
149  }
150 
151  if ( $row->fa_storage_key == '' ) {
152  // Revision was missing pre-deletion
153  $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
154  $status->failCount++;
155  continue;
156  }
157 
158  $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
159  $row->fa_storage_key;
160  $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
161 
162  if ( isset( $row->fa_sha1 ) ) {
163  $sha1 = $row->fa_sha1;
164  } else {
165  // old row, populate from key
166  $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
167  }
168 
169  # Fix leading zero
170  if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
171  $sha1 = substr( $sha1, 1 );
172  }
173 
174  if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
175  || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
176  || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
177  || is_null( $row->fa_metadata )
178  ) {
179  // Refresh our metadata
180  // Required for a new current revision; nice for older ones too. :)
181  $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
182  } else {
183  $props = [
184  'minor_mime' => $row->fa_minor_mime,
185  'major_mime' => $row->fa_major_mime,
186  'media_type' => $row->fa_media_type,
187  'metadata' => $row->fa_metadata
188  ];
189  }
190 
191  $comment = $commentStore->getComment( 'fa_description', $row );
192  $user = User::newFromAnyId( $row->fa_user, $row->fa_user_text, $row->fa_actor );
193  if ( $first && !$exists ) {
194  // This revision will be published as the new current version
195  $destRel = $this->file->getRel();
196  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
197  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
198  $insertCurrent = [
199  'img_name' => $row->fa_name,
200  'img_size' => $row->fa_size,
201  'img_width' => $row->fa_width,
202  'img_height' => $row->fa_height,
203  'img_metadata' => $props['metadata'],
204  'img_bits' => $row->fa_bits,
205  'img_media_type' => $props['media_type'],
206  'img_major_mime' => $props['major_mime'],
207  'img_minor_mime' => $props['minor_mime'],
208  'img_timestamp' => $row->fa_timestamp,
209  'img_sha1' => $sha1
210  ] + $commentFields + $actorFields;
211 
212  // The live (current) version cannot be hidden!
213  if ( !$this->unsuppress && $row->fa_deleted ) {
214  $status->fatal( 'undeleterevdel' );
215  $this->file->unlock();
216  return $status;
217  }
218  } else {
219  $archiveName = $row->fa_archive_name;
220 
221  if ( $archiveName == '' ) {
222  // This was originally a current version; we
223  // have to devise a new archive name for it.
224  // Format is <timestamp of archiving>!<name>
225  $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
226 
227  do {
228  $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
229  $timestamp++;
230  } while ( isset( $archiveNames[$archiveName] ) );
231  }
232 
233  $archiveNames[$archiveName] = true;
234  $destRel = $this->file->getArchiveRel( $archiveName );
235  $insertBatch[] = [
236  'oi_name' => $row->fa_name,
237  'oi_archive_name' => $archiveName,
238  'oi_size' => $row->fa_size,
239  'oi_width' => $row->fa_width,
240  'oi_height' => $row->fa_height,
241  'oi_bits' => $row->fa_bits,
242  'oi_timestamp' => $row->fa_timestamp,
243  'oi_metadata' => $props['metadata'],
244  'oi_media_type' => $props['media_type'],
245  'oi_major_mime' => $props['major_mime'],
246  'oi_minor_mime' => $props['minor_mime'],
247  'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
248  'oi_sha1' => $sha1
249  ] + $commentStore->insert( $dbw, 'oi_description', $comment )
250  + $actorMigration->getInsertValues( $dbw, 'oi_user', $user );
251  }
252 
253  $deleteIds[] = $row->fa_id;
254 
255  if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
256  // private files can stay where they are
257  $status->successCount++;
258  } else {
259  $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
260  $this->cleanupBatch[] = $row->fa_storage_key;
261  }
262 
263  $first = false;
264  }
265 
266  unset( $result );
267 
268  // Add a warning to the status object for missing IDs
269  $missingIds = array_diff( $this->ids, $idsPresent );
270 
271  foreach ( $missingIds as $id ) {
272  $status->error( 'undelete-missing-filearchive', $id );
273  }
274 
275  if ( !$repo->hasSha1Storage() ) {
276  // Remove missing files from batch, so we don't get errors when undeleting them
277  $checkStatus = $this->removeNonexistentFiles( $storeBatch );
278  if ( !$checkStatus->isGood() ) {
279  $status->merge( $checkStatus );
280  return $status;
281  }
282  $storeBatch = $checkStatus->value;
283 
284  // Run the store batch
285  // Use the OVERWRITE_SAME flag to smooth over a common error
286  $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
287  $status->merge( $storeStatus );
288 
289  if ( !$status->isGood() ) {
290  // Even if some files could be copied, fail entirely as that is the
291  // easiest thing to do without data loss
292  $this->cleanupFailedBatch( $storeStatus, $storeBatch );
293  $status->setOK( false );
294  $this->file->unlock();
295 
296  return $status;
297  }
298  }
299 
300  // Run the DB updates
301  // Because we have locked the image row, key conflicts should be rare.
302  // If they do occur, we can roll back the transaction at this time with
303  // no data loss, but leaving unregistered files scattered throughout the
304  // public zone.
305  // This is not ideal, which is why it's important to lock the image row.
306  if ( $insertCurrent ) {
307  $dbw->insert( 'image', $insertCurrent, __METHOD__ );
308  }
309 
310  if ( $insertBatch ) {
311  $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
312  }
313 
314  if ( $deleteIds ) {
315  $dbw->delete( 'filearchive',
316  [ 'fa_id' => $deleteIds ],
317  __METHOD__ );
318  }
319 
320  // If store batch is empty (all files are missing), deletion is to be considered successful
321  if ( $status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
322  if ( !$exists ) {
323  wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
324 
326 
327  $this->file->purgeEverything();
328  } else {
329  wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
330  $this->file->purgeDescription();
331  }
332  }
333 
334  $this->file->unlock();
335 
336  return $status;
337  }
338 
344  protected function removeNonexistentFiles( $triplets ) {
345  $files = $filteredTriplets = [];
346  foreach ( $triplets as $file ) {
347  $files[$file[0]] = $file[0];
348  }
349 
350  $result = $this->file->repo->fileExistsBatch( $files );
351  if ( in_array( null, $result, true ) ) {
352  return Status::newFatal( 'backend-fail-internal',
353  $this->file->repo->getBackend()->getName() );
354  }
355 
356  foreach ( $triplets as $file ) {
357  if ( $result[$file[0]] ) {
358  $filteredTriplets[] = $file;
359  }
360  }
361 
362  return Status::newGood( $filteredTriplets );
363  }
364 
370  protected function removeNonexistentFromCleanup( $batch ) {
371  $files = $newBatch = [];
372  $repo = $this->file->repo;
373 
374  foreach ( $batch as $file ) {
375  $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
376  rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
377  }
378 
379  $result = $repo->fileExistsBatch( $files );
380 
381  foreach ( $batch as $file ) {
382  if ( $result[$file] ) {
383  $newBatch[] = $file;
384  }
385  }
386 
387  return $newBatch;
388  }
389 
395  public function cleanup() {
396  if ( !$this->cleanupBatch ) {
397  return $this->file->repo->newGood();
398  }
399 
400  $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
401 
402  $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
403 
404  return $status;
405  }
406 
414  protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
415  $cleanupBatch = [];
416 
417  foreach ( $storeStatus->success as $i => $success ) {
418  // Check if this item of the batch was successfully copied
419  if ( $success ) {
420  // Item was successfully copied and needs to be removed again
421  // Extract ($dstZone, $dstRel) from the batch
422  $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
423  }
424  }
425  $this->file->repo->cleanupBatch( $cleanupBatch );
426  }
427 }
$success
addAll()
Add all revisions of the file.
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new archivedfile object...
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
cleanup()
Delete unused files in the deleted zone.
static newFromAnyId( $userId, $userName, $actorId, $dbDomain=false)
Static factory method for creation from an ID, name, and/or actor ID.
Definition: User.php:627
Helper class for file undeletion.
removeNonexistentFromCleanup( $batch)
Removes non-existent files from a cleanup batch.
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 MediaWikiServices
Definition: injection.txt:23
string [] $ids
List of file IDs to restore.
const DELETED_FILE
Definition: File.php:63
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. '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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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:Array with elements of the form "language:title" in the order that they will be output. & $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 since 1.28! 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:1969
$batch
Definition: linkcache.txt:23
addIds( $ids)
Add a whole lot of files by ID.
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
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 '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:1244
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
__construct(File $file, $unsuppress=false)
$wgLang
Definition: Setup.php:940
static newMigration()
Static constructor.
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
Definition: hooks.txt:91
static factory(array $deltas)
static singleton()
Definition: RepoGroup.php:60
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
bool $unsuppress
Whether to remove all settings for suppressed fields.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
bool $all
Add all revisions of the file.
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
static getHashFromKey( $key)
Gets the SHA1 hash from a storage key.
Definition: LocalRepo.php:182
removeNonexistentFiles( $triplets)
Removes non-existent files from a store batch.
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
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
const OVERWRITE_SAME
Definition: FileRepo.php:42
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:61
string [] $cleanupBatch
List of file IDs to restore.
cleanupFailedBatch( $storeStatus, $storeBatch)
Cleanup a failed batch.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
execute()
Run the transaction, except the cleanup batch.
addId( $fa_id)
Add a file by ID.