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