MediaWiki  master
RefreshLinksJob.php
Go to the documentation of this file.
1 <?php
24 
38 class RefreshLinksJob extends Job {
40  const PARSE_THRESHOLD_SEC = 1.0;
42  const CLOCK_FUDGE = 10;
44  const LAG_WAIT_TIMEOUT = 15;
45 
47  parent::__construct( 'refreshLinks', $title, $params );
48  // Avoid the overhead of de-duplication when it would be pointless
49  $this->removeDuplicates = (
50  // Ranges rarely will line up
51  !isset( $params['range'] ) &&
52  // Multiple pages per job make matches unlikely
53  !( isset( $params['pages'] ) && count( $params['pages'] ) != 1 )
54  );
55  }
56 
62  public static function newPrioritized( Title $title, array $params ) {
63  $job = new self( $title, $params );
64  $job->command = 'refreshLinksPrioritized';
65 
66  return $job;
67  }
68 
74  public static function newDynamic( Title $title, array $params ) {
75  $job = new self( $title, $params );
76  $job->command = 'refreshLinksDynamic';
77 
78  return $job;
79  }
80 
81  function run() {
83 
84  // Job to update all (or a range of) backlink pages for a page
85  if ( !empty( $this->params['recursive'] ) ) {
86  // When the base job branches, wait for the slaves to catch up to the master.
87  // From then on, we know that any template changes at the time the base job was
88  // enqueued will be reflected in backlink page parses when the leaf jobs run.
89  if ( !isset( $params['range'] ) ) {
90  try {
91  wfGetLBFactory()->waitForReplication( [
92  'wiki' => wfWikiID(),
93  'timeout' => self::LAG_WAIT_TIMEOUT
94  ] );
95  } catch ( DBReplicationWaitError $e ) { // only try so hard
96  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
97  $stats->increment( 'refreshlinks.lag_wait_failed' );
98  }
99  }
100  // Carry over information for de-duplication
101  $extraParams = $this->getRootJobParams();
102  $extraParams['triggeredRecursive'] = true;
103  // Convert this into no more than $wgUpdateRowsPerJob RefreshLinks per-title
104  // jobs and possibly a recursive RefreshLinks job for the rest of the backlinks
106  $this,
107  $wgUpdateRowsPerJob,
108  1, // job-per-title
109  [ 'params' => $extraParams ]
110  );
111  JobQueueGroup::singleton()->push( $jobs );
112  // Job to update link tables for a set of titles
113  } elseif ( isset( $this->params['pages'] ) ) {
114  foreach ( $this->params['pages'] as $pageId => $nsAndKey ) {
115  list( $ns, $dbKey ) = $nsAndKey;
116  $this->runForTitle( Title::makeTitleSafe( $ns, $dbKey ) );
117  }
118  // Job to update link tables for a given title
119  } else {
120  $this->runForTitle( $this->title );
121  }
122 
123  return true;
124  }
125 
130  protected function runForTitle( Title $title ) {
131  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
132 
133  $page = WikiPage::factory( $title );
134  $page->loadPageData( WikiPage::READ_LATEST );
135 
136  // Serialize links updates by page ID so they see each others' changes
137  $scopedLock = LinksUpdate::acquirePageLock( wfGetDB( DB_MASTER ), $page->getId(), 'job' );
138  // Get the latest ID *after* acquirePageLock() flushed the transaction.
139  // This is used to detect edits/moves after loadPageData() but before the scope lock.
140  // The works around the chicken/egg problem of determining the scope lock key.
141  $latest = $title->getLatestRevID( Title::GAID_FOR_UPDATE );
142 
143  if ( !empty( $this->params['triggeringRevisionId'] ) ) {
144  // Fetch the specified revision; lockAndGetLatest() below detects if the page
145  // was edited since and aborts in order to avoid corrupting the link tables
146  $revision = Revision::newFromId(
147  $this->params['triggeringRevisionId'],
149  );
150  } else {
151  // Fetch current revision; READ_LATEST reduces lockAndGetLatest() check failures
152  $revision = Revision::newFromTitle( $title, false, Revision::READ_LATEST );
153  }
154 
155  if ( !$revision ) {
156  $stats->increment( 'refreshlinks.rev_not_found' );
157  $this->setLastError( "Revision not found for {$title->getPrefixedDBkey()}" );
158  return false; // just deleted?
159  } elseif ( $revision->getId() != $latest || $revision->getPage() !== $page->getId() ) {
160  // Do not clobber over newer updates with older ones. If all jobs where FIFO and
161  // serialized, it would be OK to update links based on older revisions since it
162  // would eventually get to the latest. Since that is not the case (by design),
163  // only update the link tables to a state matching the current revision's output.
164  $stats->increment( 'refreshlinks.rev_not_current' );
165  $this->setLastError( "Revision {$revision->getId()} is not current" );
166  return false;
167  }
168 
169  $content = $revision->getContent( Revision::RAW );
170  if ( !$content ) {
171  // If there is no content, pretend the content is empty
172  $content = $revision->getContentHandler()->makeEmptyContent();
173  }
174 
175  $parserOutput = false;
176  $parserOptions = $page->makeParserOptions( 'canonical' );
177  // If page_touched changed after this root job, then it is likely that
178  // any views of the pages already resulted in re-parses which are now in
179  // cache. The cache can be reused to avoid expensive parsing in some cases.
180  if ( isset( $this->params['rootJobTimestamp'] ) ) {
181  $opportunistic = !empty( $this->params['isOpportunistic'] );
182 
183  $skewedTimestamp = $this->params['rootJobTimestamp'];
184  if ( $opportunistic ) {
185  // Neither clock skew nor DB snapshot/slave lag matter much for such
186  // updates; focus on reusing the (often recently updated) cache
187  } else {
188  // For transclusion updates, the template changes must be reflected
189  $skewedTimestamp = wfTimestamp( TS_MW,
190  wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
191  );
192  }
193 
194  if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
195  // Something already updated the backlinks since this job was made
196  $stats->increment( 'refreshlinks.update_skipped' );
197  return true;
198  }
199 
200  if ( $page->getTouched() >= $this->params['rootJobTimestamp'] || $opportunistic ) {
201  // Cache is suspected to be up-to-date. As long as the cache rev ID matches
202  // and it reflects the job's triggering change, then it is usable.
203  $parserOutput = ParserCache::singleton()->getDirty( $page, $parserOptions );
204  if ( !$parserOutput
205  || $parserOutput->getCacheRevisionId() != $revision->getId()
206  || $parserOutput->getCacheTime() < $skewedTimestamp
207  ) {
208  $parserOutput = false; // too stale
209  }
210  }
211  }
212 
213  // Fetch the current revision and parse it if necessary...
214  if ( $parserOutput ) {
215  $stats->increment( 'refreshlinks.parser_cached' );
216  } else {
217  $start = microtime( true );
218  // Revision ID must be passed to the parser output to get revision variables correct
219  $parserOutput = $content->getParserOutput(
220  $title, $revision->getId(), $parserOptions, false );
221  $elapsed = microtime( true ) - $start;
222  // If it took a long time to render, then save this back to the cache to avoid
223  // wasted CPU by other apaches or job runners. We don't want to always save to
224  // cache as this can cause high cache I/O and LRU churn when a template changes.
225  if ( $elapsed >= self::PARSE_THRESHOLD_SEC
226  && $page->shouldCheckParserCache( $parserOptions, $revision->getId() )
227  && $parserOutput->isCacheable()
228  ) {
229  $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
230  ParserCache::singleton()->save(
231  $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
232  );
233  }
234  $stats->increment( 'refreshlinks.parser_uncached' );
235  }
236 
237  $updates = $content->getSecondaryDataUpdates(
238  $title,
239  null,
240  !empty( $this->params['useRecursiveLinksUpdate'] ),
242  );
243 
244  foreach ( $updates as $key => $update ) {
245  // FIXME: This code probably shouldn't be here?
246  // Needed by things like Echo notifications which need
247  // to know which user caused the links update
248  if ( $update instanceof LinksUpdate ) {
249  $update->setRevision( $revision );
250  if ( !empty( $this->params['triggeringUser'] ) ) {
251  $userInfo = $this->params['triggeringUser'];
252  if ( $userInfo['userId'] ) {
253  $user = User::newFromId( $userInfo['userId'] );
254  } else {
255  // Anonymous, use the username
256  $user = User::newFromName( $userInfo['userName'], false );
257  }
258  $update->setTriggeringUser( $user );
259  }
260  }
261  }
262 
263  DataUpdate::runUpdates( $updates );
264 
265  InfoAction::invalidateCache( $title );
266 
267  return true;
268  }
269 
270  public function getDeduplicationInfo() {
271  $info = parent::getDeduplicationInfo();
272  if ( is_array( $info['params'] ) ) {
273  // For per-pages jobs, the job title is that of the template that changed
274  // (or similar), so remove that since it ruins duplicate detection
275  if ( isset( $info['pages'] ) ) {
276  unset( $info['namespace'] );
277  unset( $info['title'] );
278  }
279  }
280 
281  return $info;
282  }
283 
284  public function workItemCount() {
285  return isset( $this->params['pages'] ) ? count( $this->params['pages'] ) : 1;
286  }
287 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:522
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:101
getLatestRevID($flags=0)
What is the page_latest field for this page?
Definition: Title.php:3230
__construct(Title $title, array $params)
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
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Class the manages updates of *_link tables as well as similar extension-managed tables.
Definition: LinksUpdate.php:30
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
$wgUpdateRowsPerJob
Number of rows to update per job.
Class to both describe a background job and handle jobs.
Definition: Job.php:31
static newFromId($id)
Static factory method for creation from a given user ID.
Definition: User.php:545
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
Represents a title within MediaWiki.
Definition: Title.php:36
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target...
Definition: Revision.php:117
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
runForTitle(Title $title)
static runUpdates(array $updates, $mode= 'run')
Convenience method, calls doUpdate() on every DataUpdate in the array.
Definition: DataUpdate.php:77
static invalidateCache(Title $title, $revid=null)
Clear the info cache for a given Title.
Definition: InfoAction.php:69
Exception class for replica DB wait timeouts.
Definition: LBFactory.php:472
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 and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context $parserOutput
Definition: hooks.txt:1020
getRootJobParams()
Definition: Job.php:274
const GAID_FOR_UPDATE
Used to be GAID_FOR_UPDATE define.
Definition: Title.php:51
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:527
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
const RAW
Definition: Revision.php:85
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
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
static singleton($wiki=false)
static singleton()
Get an instance of this object.
Definition: ParserCache.php:36
Job to update link tables for pages.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
static newFromId($id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:99
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 newDynamic(Title $title, array $params)
wfGetLBFactory()
Get the load balancer factory object.
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 and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1020
if(count($args)< 1) $job
setLastError($error)
Definition: Job.php:391
getDeduplicationInfo()
Subclasses may need to override this to make duplication detection work.
static newPrioritized(Title $title, array $params)
to move a page</td >< td > &*You are moving the page across *A non empty talk page already exists under the new or *You uncheck the box below In those you will have to move or merge the page manually if desired</td >< td > be sure to &You are responsible for making sure that links continue to point where they are supposed to go Note that the page will &a page at the new title
array $params
Array of job parameters.
Definition: Job.php:36
const DB_MASTER
Definition: Defines.php:47
static partitionBacklinkJob(Job $job, $bSize, $cSize, $opts=[])
Break down $job into approximately ($bSize/$cSize) leaf jobs and a single partition job that covers t...
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
static acquirePageLock(IDatabase $dbw, $pageId, $why= 'atomicity')
Acquire a lock for performing link table updates for a page on a DB.
Title $title
Definition: Job.php:42
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2376