MediaWiki  1.28.0
CategoryMembershipChangeJob.php
Go to the documentation of this file.
1 <?php
23 
37  private $ticket;
38 
39  const ENQUEUE_FUDGE_SEC = 60;
40 
41  public function __construct( Title $title, array $params ) {
42  parent::__construct( 'categoryMembershipChange', $title, $params );
43  // Only need one job per page. Note that ENQUEUE_FUDGE_SEC handles races where an
44  // older revision job gets inserted while the newer revision job is de-duplicated.
45  $this->removeDuplicates = true;
46  }
47 
48  public function run() {
49  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
50  $lb = $lbFactory->getMainLB();
51  $dbw = $lb->getConnection( DB_MASTER );
52 
53  $this->ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
54 
55  $page = WikiPage::newFromID( $this->params['pageId'], WikiPage::READ_LATEST );
56  if ( !$page ) {
57  $this->setLastError( "Could not find page #{$this->params['pageId']}" );
58  return false; // deleted?
59  }
60 
61  // Use a named lock so that jobs for this page see each others' changes
62  $lockKey = "CategoryMembershipUpdates:{$page->getId()}";
63  $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 3 );
64  if ( !$scopedLock ) {
65  $this->setLastError( "Could not acquire lock '$lockKey'" );
66  return false;
67  }
68 
69  $dbr = $lb->getConnection( DB_REPLICA, [ 'recentchanges' ] );
70  // Wait till the replica DB is caught up so that jobs for this page see each others' changes
71  if ( !$lb->safeWaitForMasterPos( $dbr ) ) {
72  $this->setLastError( "Timed out while waiting for replica DB to catch up" );
73  return false;
74  }
75  // Clear any stale REPEATABLE-READ snapshot
76  $dbr->flushSnapshot( __METHOD__ );
77 
78  $cutoffUnix = wfTimestamp( TS_UNIX, $this->params['revTimestamp'] );
79  // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
80  // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
81  $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
82 
83  // Get the newest revision that has a SRC_CATEGORIZE row...
84  $row = $dbr->selectRow(
85  [ 'revision', 'recentchanges' ],
86  [ 'rev_timestamp', 'rev_id' ],
87  [
88  'rev_page' => $page->getId(),
89  'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) )
90  ],
91  __METHOD__,
92  [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC' ],
93  [
94  'recentchanges' => [
95  'INNER JOIN',
96  [
97  'rc_this_oldid = rev_id',
98  'rc_source' => RecentChange::SRC_CATEGORIZE,
99  // Allow rc_cur_id or rc_timestamp index usage
100  'rc_cur_id = rev_page',
101  'rc_timestamp >= rev_timestamp'
102  ]
103  ]
104  ]
105  );
106  // Only consider revisions newer than any such revision
107  if ( $row ) {
108  $cutoffUnix = wfTimestamp( TS_UNIX, $row->rev_timestamp );
109  $lastRevId = (int)$row->rev_id;
110  } else {
111  $lastRevId = 0;
112  }
113 
114  // Find revisions to this page made around and after this revision which lack category
115  // notifications in recent changes. This lets jobs pick up were the last one left off.
116  $encCutoff = $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) );
117  $res = $dbr->select(
118  'revision',
120  [
121  'rev_page' => $page->getId(),
122  "rev_timestamp > $encCutoff" .
123  " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
124  ],
125  __METHOD__,
126  [ 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC' ]
127  );
128 
129  // Apply all category updates in revision timestamp order
130  foreach ( $res as $row ) {
132  }
133 
134  return true;
135  }
136 
143  protected function notifyUpdatesForRevision(
145  ) {
146  $config = RequestContext::getMain()->getConfig();
147  $title = $page->getTitle();
148 
149  // Get the new revision
150  if ( !$newRev->getContent() ) {
151  return; // deleted?
152  }
153 
154  // Get the prior revision (the same for null edits)
155  if ( $newRev->getParentId() ) {
156  $oldRev = Revision::newFromId( $newRev->getParentId(), Revision::READ_LATEST );
157  if ( !$oldRev->getContent() ) {
158  return; // deleted?
159  }
160  } else {
161  $oldRev = null;
162  }
163 
164  // Parse the new revision and get the categories
165  $categoryChanges = $this->getExplicitCategoriesChanges( $title, $newRev, $oldRev );
166  list( $categoryInserts, $categoryDeletes ) = $categoryChanges;
167  if ( !$categoryInserts && !$categoryDeletes ) {
168  return; // nothing to do
169  }
170 
171  $catMembChange = new CategoryMembershipChange( $title, $newRev );
172  $catMembChange->checkTemplateLinks();
173 
174  $batchSize = $config->get( 'UpdateRowsPerQuery' );
175  $insertCount = 0;
176 
177  foreach ( $categoryInserts as $categoryName ) {
178  $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
179  $catMembChange->triggerCategoryAddedNotification( $categoryTitle );
180  if ( $insertCount++ && ( $insertCount % $batchSize ) == 0 ) {
181  $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
182  }
183  }
184 
185  foreach ( $categoryDeletes as $categoryName ) {
186  $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
187  $catMembChange->triggerCategoryRemovedNotification( $categoryTitle );
188  if ( $insertCount++ && ( $insertCount++ % $batchSize ) == 0 ) {
189  $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
190  }
191  }
192  }
193 
195  Title $title, Revision $newRev, Revision $oldRev = null
196  ) {
197  // Inject the same timestamp for both revision parses to avoid seeing category changes
198  // due to time-based parser functions. Inject the same page title for the parses too.
199  // Note that REPEATABLE-READ makes template/file pages appear unchanged between parses.
200  $parseTimestamp = $newRev->getTimestamp();
201  // Parse the old rev and get the categories. Do not use link tables as that
202  // assumes these updates are perfectly FIFO and that link tables are always
203  // up to date, neither of which are true.
204  $oldCategories = $oldRev
205  ? $this->getCategoriesAtRev( $title, $oldRev, $parseTimestamp )
206  : [];
207  // Parse the new revision and get the categories
208  $newCategories = $this->getCategoriesAtRev( $title, $newRev, $parseTimestamp );
209 
210  $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
211  $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
212 
213  return [ $categoryInserts, $categoryDeletes ];
214  }
215 
223  private function getCategoriesAtRev( Title $title, Revision $rev, $parseTimestamp ) {
224  $content = $rev->getContent();
225  $options = $content->getContentHandler()->makeParserOptions( 'canonical' );
226  $options->setTimestamp( $parseTimestamp );
227  // This could possibly use the parser cache if it checked the revision ID,
228  // but that's more complicated than it's worth.
229  $output = $content->getParserOutput( $title, $rev->getId(), $options );
230 
231  // array keys will cast numeric category names to ints
232  // so we need to cast them back to strings to avoid breaking things!
233  return array_map( 'strval', array_keys( $output->getCategories() ) );
234  }
235 
236  public function getDeduplicationInfo() {
237  $info = parent::getDeduplicationInfo();
238  unset( $info['params']['revTimestamp'] ); // first job wins
239 
240  return $info;
241  }
242 }
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.
const SRC_CATEGORIZE
__construct(Title $title, array $params)
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getTimestamp()
Definition: Revision.php:1194
notifyUpdatesForRevision(LBFactory $lbFactory, WikiPage $page, Revision $newRev)
getDeduplicationInfo()
Subclasses may need to override this to make duplication detection work.
Class to both describe a background job and handle jobs.
Definition: Job.php:31
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
const DB_MASTER
Definition: defines.php:23
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Definition: defines.php:6
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static getMain()
Static methods.
getParentId()
Get parent revision ID (the original previous page revision)
Definition: Revision.php:774
getId()
Get revision ID.
Definition: Revision.php:729
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 as context as context $options
Definition: hooks.txt:1046
$res
Definition: database.txt:21
getCategoriesAtRev(Title $title, Revision $rev, $parseTimestamp)
getTitle()
Get the title object of the article.
Definition: WikiPage.php:232
const NS_CATEGORY
Definition: Defines.php:70
static selectFields()
Return the list of revision fields that should be selected to create a new revision.
Definition: Revision.php:442
getExplicitCategoriesChanges(Title $title, Revision $newRev, Revision $oldRev=null)
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1721
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
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 as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1046
Class representing a MediaWiki article and history.
Definition: WikiPage.php:32
static newFromId($id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:110
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
commitAndWaitForReplication($fname, $ticket, array $opts=[])
Convenience method for safely running commitMasterChanges()/waitForReplication()
Definition: LBFactory.php:383
Job to add recent change entries mentioning category membership changes.
$lbFactory
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:1046
setLastError($error)
Definition: Job.php:393
getContent($audience=self::FOR_PUBLIC, User $user=null)
Fetch revision content if it's available to the specified audience.
Definition: Revision.php:1073
static newFromRow($row)
Definition: Revision.php:230
static newFromID($id, $from= 'fromdb')
Constructor from a page id.
Definition: WikiPage.php:153
array $params
Array of job parameters.
Definition: Job.php:36
const DB_REPLICA
Definition: defines.php:22
Title $title
Definition: Job.php:42
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:511
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:2491