MediaWiki  master
DoubleRedirectJob.php
Go to the documentation of this file.
1 <?php
27 
33 class DoubleRedirectJob extends Job {
39  public const MAX_DR_JOBS_COUNTER = 10000;
40 
44  private $redirTitle;
45 
47  private static $user;
48 
58  public function __construct( PageReference $page, array $params ) {
59  parent::__construct( 'fixDoubleRedirect', $page, $params );
60  $this->redirTitle = Title::newFromText( $params['redirTitle'] );
61  }
62 
70  public static function fixRedirects( $reason, $redirTitle ) {
71  # Need to use the primary DB to get the redirect table updated in the same transaction
72  $dbw = wfGetDB( DB_PRIMARY );
73  $res = $dbw->select(
74  [ 'redirect', 'page' ],
75  [ 'page_namespace', 'page_title' ],
76  [
77  'page_id = rd_from',
78  'rd_namespace' => $redirTitle->getNamespace(),
79  'rd_title' => $redirTitle->getDBkey()
80  ], __METHOD__ );
81  if ( !$res->numRows() ) {
82  return;
83  }
84  $jobs = [];
85  $jobQueueGroup = MediaWikiServices::getInstance()->getJobQueueGroup();
86  foreach ( $res as $row ) {
87  $title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
88  if ( !$title || !$title->canExist() ) {
89  continue;
90  }
91 
92  $jobs[] = new self( $title, [
93  'reason' => $reason,
94  'redirTitle' => MediaWikiServices::getInstance()
95  ->getTitleFormatter()
96  ->getPrefixedDBkey( $redirTitle ),
97  ] );
98  # Avoid excessive memory usage
99  if ( count( $jobs ) > self::MAX_DR_JOBS_COUNTER ) {
100  $jobQueueGroup->push( $jobs );
101  $jobs = [];
102  }
103  }
104  $jobQueueGroup->push( $jobs );
105  }
106 
110  public function run() {
111  if ( !$this->redirTitle ) {
112  $this->setLastError( 'Invalid title' );
113 
114  return false;
115  }
116 
117  if ( !$this->title->canExist() ) {
118  // Needs a proper title for WikiPageFactory::newFromTitle and RevisionStore::getRevisionByTitle
119  $this->setLastError( 'Cannot edit title' );
120 
121  return false;
122  }
123 
124  $services = MediaWikiServices::getInstance();
125  $targetRev = $services->getRevisionLookup()
126  ->getRevisionByTitle( $this->title, 0, RevisionLookup::READ_LATEST );
127  if ( !$targetRev ) {
128  wfDebug( __METHOD__ . ": target redirect already deleted, ignoring" );
129 
130  return true;
131  }
132  $content = $targetRev->getContent( SlotRecord::MAIN );
133  $currentDest = $content ? $content->getRedirectTarget() : null;
134  if ( !$currentDest || !$currentDest->equals( $this->redirTitle ) ) {
135  wfDebug( __METHOD__ . ": Redirect has changed since the job was queued" );
136 
137  return true;
138  }
139 
140  // Check for a suppression tag (used e.g. in periodically archived discussions)
141  $mw = $services->getMagicWordFactory()->get( 'staticredirect' );
142  if ( $content->matchMagicWord( $mw ) ) {
143  wfDebug( __METHOD__ . ": skipping: suppressed with __STATICREDIRECT__" );
144 
145  return true;
146  }
147 
148  // Find the current final destination
149  $newTitle = self::getFinalDestination( $this->redirTitle );
150  if ( !$newTitle ) {
151  wfDebug( __METHOD__ .
152  ": skipping: single redirect, circular redirect or invalid redirect destination" );
153 
154  return true;
155  }
156  if ( $newTitle->equals( $this->redirTitle ) ) {
157  // The redirect is already right, no need to change it
158  // This can happen if the page was moved back (say after vandalism)
159  wfDebug( __METHOD__ . " : skipping, already good" );
160  }
161 
162  // Preserve fragment (T16904)
163  $newTitle = Title::makeTitle( $newTitle->getNamespace(), $newTitle->getDBkey(),
164  $currentDest->getFragment(), $newTitle->getInterwiki() );
165 
166  // Fix the text
167  $newContent = $content->updateRedirect( $newTitle );
168 
169  if ( $newContent->equals( $content ) ) {
170  $this->setLastError( 'Content unchanged???' );
171 
172  return false;
173  }
174 
175  $user = $this->getUser();
176  if ( !$user ) {
177  $this->setLastError( 'Invalid user' );
178 
179  return false;
180  }
181 
182  // Save it
183  // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgUser
184  global $wgUser;
185  $oldUser = $wgUser;
186  $wgUser = $user;
187  $article = $services->getWikiPageFactory()->newFromTitle( $this->title );
188 
189  // Messages: double-redirect-fixed-move, double-redirect-fixed-maintenance
190  $reason = wfMessage( 'double-redirect-fixed-' . $this->params['reason'],
191  $this->redirTitle->getPrefixedText(), $newTitle->getPrefixedText()
192  )->inContentLanguage()->text();
193  // Avoid RC flood, and use minor to avoid email notifs
195  $article->doUserEditContent( $newContent, $user, $reason, $flags );
196  $wgUser = $oldUser;
197 
198  return true;
199  }
200 
209  public static function getFinalDestination( $title ) {
210  $dbw = wfGetDB( DB_PRIMARY );
211 
212  // Circular redirect check
213  $seenTitles = [];
214  $dest = false;
215 
216  while ( true ) {
217  $titleText = CacheKeyHelper::getKeyForPage( $title );
218  if ( isset( $seenTitles[$titleText] ) ) {
219  wfDebug( __METHOD__, "Circular redirect detected, aborting" );
220 
221  return false;
222  }
223  $seenTitles[$titleText] = true;
224 
225  if ( $title->isExternal() ) {
226  // If the target is interwiki, we have to break early (T42352).
227  // Otherwise it will look up a row in the local page table
228  // with the namespace/page of the interwiki target which can cause
229  // unexpected results (e.g. X -> foo:Bar -> Bar -> .. )
230  break;
231  }
232 
233  $row = $dbw->selectRow(
234  [ 'redirect', 'page' ],
235  [ 'rd_namespace', 'rd_title', 'rd_interwiki' ],
236  [
237  'rd_from=page_id',
238  'page_namespace' => $title->getNamespace(),
239  'page_title' => $title->getDBkey()
240  ], __METHOD__ );
241  if ( !$row ) {
242  # No redirect from here, chain terminates
243  break;
244  } else {
245  $dest = $title = Title::makeTitle(
246  $row->rd_namespace,
247  $row->rd_title,
248  '',
249  $row->rd_interwiki ?? ''
250  );
251  }
252  }
253 
254  return $dest;
255  }
256 
264  private function getUser() {
265  if ( !self::$user ) {
266  $username = wfMessage( 'double-redirect-fixer' )->inContentLanguage()->text();
267  self::$user = User::newFromName( $username );
268  # User::newFromName() can return false on a badly configured wiki.
269  if ( self::$user && !self::$user->isRegistered() ) {
270  self::$user->addToDatabase();
271  }
272  }
273 
274  return self::$user;
275  }
276 }
const EDIT_INTERNAL
Definition: Defines.php:133
const EDIT_UPDATE
Definition: Defines.php:127
const EDIT_SUPPRESS_RC
Definition: Defines.php:129
const EDIT_MINOR
Definition: Defines.php:128
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
$wgUser
Definition: Setup.php:500
Fix any double redirects after moving a page.
static getFinalDestination( $title)
Get the final destination of a redirect.
__construct(PageReference $page, array $params)
static fixRedirects( $reason, $redirTitle)
Insert jobs into the job queue to fix redirects to the given title.
Class to both describe a background job and handle jobs.
Definition: Job.php:39
Title $title
Definition: Job.php:50
setLastError( $error)
Definition: Job.php:469
array $params
Array of job parameters.
Definition: Job.php:44
Helper class for mapping value objects representing basic entities to cache keys.
Service locator for MediaWiki core services.
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:40
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:1069
canExist()
Can this title represent a page in the wiki's database?
Definition: Title.php:1235
isExternal()
Is this Title interwiki?
Definition: Title.php:959
getDBkey()
Get the main part with underscores.
Definition: Title.php:1060
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:373
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:667
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:641
static newFromName( $name, $validate='valid')
Definition: User.php:587
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Service for looking up page revisions.
const DB_PRIMARY
Definition: defines.php:28
$content
Definition: router.php:76