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