Merge "Made master connection expectations actually work"
[lhc/web/wiklou.git] / includes / MovePage.php
1 <?php
2
3 /**
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
18 *
19 * @file
20 */
21
22 /**
23 * Handles the backend logic of moving a page from one title
24 * to another.
25 *
26 * @since 1.24
27 */
28 class MovePage {
29
30 /**
31 * @var Title
32 */
33 protected $oldTitle;
34
35 /**
36 * @var Title
37 */
38 protected $newTitle;
39
40 public function __construct( Title $oldTitle, Title $newTitle ) {
41 $this->oldTitle = $oldTitle;
42 $this->newTitle = $newTitle;
43 }
44
45 public function checkPermissions( User $user, $reason ) {
46 $status = new Status();
47
48 $errors = wfMergeErrorArrays(
49 $this->oldTitle->getUserPermissionsErrors( 'move', $user ),
50 $this->oldTitle->getUserPermissionsErrors( 'edit', $user ),
51 $this->newTitle->getUserPermissionsErrors( 'move-target', $user ),
52 $this->newTitle->getUserPermissionsErrors( 'edit', $user )
53 );
54
55 // Convert into a Status object
56 if ( $errors ) {
57 foreach ( $errors as $error ) {
58 call_user_func_array( array( $status, 'fatal' ), $error );
59 }
60 }
61
62 if ( EditPage::matchSummarySpamRegex( $reason ) !== false ) {
63 // This is kind of lame, won't display nice
64 $status->fatal( 'spamprotectiontext' );
65 }
66
67 # The move is allowed only if (1) the target doesn't exist, or
68 # (2) the target is a redirect to the source, and has no history
69 # (so we can undo bad moves right after they're done).
70
71 if ( $this->newTitle->getArticleID() ) { # Target exists; check for validity
72 if ( !$this->isValidMoveTarget() ) {
73 $status->fatal( 'articleexists' );
74 }
75 } else {
76 $tp = $this->newTitle->getTitleProtection();
77 if ( $tp !== false ) {
78 if ( !$user->isAllowed( $tp['permission'] ) ) {
79 $status->fatal( 'cantmove-titleprotected' );
80 }
81 }
82 }
83
84 Hooks::run( 'MovePageCheckPermissions',
85 array( $this->oldTitle, $this->newTitle, $user, $reason, $status )
86 );
87
88 return $status;
89 }
90
91 /**
92 * Does various sanity checks that the move is
93 * valid. Only things based on the two titles
94 * should be checked here.
95 *
96 * @return Status
97 */
98 public function isValidMove() {
99 global $wgContentHandlerUseDB;
100 $status = new Status();
101
102 if ( $this->oldTitle->equals( $this->newTitle ) ) {
103 $status->fatal( 'selfmove' );
104 }
105 if ( !$this->oldTitle->isMovable() ) {
106 $status->fatal( 'immobile-source-namespace', $this->oldTitle->getNsText() );
107 }
108 if ( $this->newTitle->isExternal() ) {
109 $status->fatal( 'immobile-target-namespace-iw' );
110 }
111 if ( !$this->newTitle->isMovable() ) {
112 $status->fatal( 'immobile-target-namespace', $this->newTitle->getNsText() );
113 }
114
115 $oldid = $this->oldTitle->getArticleID();
116
117 if ( strlen( $this->newTitle->getDBkey() ) < 1 ) {
118 $status->fatal( 'articleexists' );
119 }
120 if (
121 ( $this->oldTitle->getDBkey() == '' ) ||
122 ( !$oldid ) ||
123 ( $this->newTitle->getDBkey() == '' )
124 ) {
125 $status->fatal( 'badarticleerror' );
126 }
127
128 // Content model checks
129 if ( !$wgContentHandlerUseDB &&
130 $this->oldTitle->getContentModel() !== $this->newTitle->getContentModel() ) {
131 // can't move a page if that would change the page's content model
132 $status->fatal(
133 'bad-target-model',
134 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
135 ContentHandler::getLocalizedName( $this->newTitle->getContentModel() )
136 );
137 }
138
139 // Image-specific checks
140 if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
141 $status->merge( $this->isValidFileMove() );
142 }
143
144 if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
145 $status->fatal( 'nonfile-cannot-move-to-file' );
146 }
147
148 // Hook for extensions to say a title can't be moved for technical reasons
149 Hooks::run( 'MovePageIsValidMove', array( $this->oldTitle, $this->newTitle, $status ) );
150
151 return $status;
152 }
153
154 /**
155 * Sanity checks for when a file is being moved
156 *
157 * @return Status
158 */
159 protected function isValidFileMove() {
160 $status = new Status();
161 $file = wfLocalFile( $this->oldTitle );
162 if ( $file->exists() ) {
163 if ( $this->newTitle->getText() != wfStripIllegalFilenameChars( $this->newTitle->getText() ) ) {
164 $status->fatal( 'imageinvalidfilename' );
165 }
166 if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
167 $status->fatal( 'imagetypemismatch' );
168 }
169 }
170
171 if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
172 $status->fatal( 'imagenocrossnamespace' );
173 }
174
175 return $status;
176 }
177
178 /**
179 * Checks if $this can be moved to a given Title
180 * - Selects for update, so don't call it unless you mean business
181 *
182 * @since 1.25
183 * @return bool
184 */
185 protected function isValidMoveTarget() {
186 # Is it an existing file?
187 if ( $this->newTitle->inNamespace( NS_FILE ) ) {
188 $file = wfLocalFile( $this->newTitle );
189 if ( $file->exists() ) {
190 wfDebug( __METHOD__ . ": file exists\n" );
191 return false;
192 }
193 }
194 # Is it a redirect with no history?
195 if ( !$this->newTitle->isSingleRevRedirect() ) {
196 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
197 return false;
198 }
199 # Get the article text
200 $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
201 if ( !is_object( $rev ) ) {
202 return false;
203 }
204 $content = $rev->getContent();
205 # Does the redirect point to the source?
206 # Or is it a broken self-redirect, usually caused by namespace collisions?
207 $redirTitle = $content ? $content->getRedirectTarget() : null;
208
209 if ( $redirTitle ) {
210 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
211 $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
212 wfDebug( __METHOD__ . ": redirect points to other page\n" );
213 return false;
214 } else {
215 return true;
216 }
217 } else {
218 # Fail safe (not a redirect after all. strange.)
219 wfDebug( __METHOD__ . ": failsafe: database says " . $this->newTitle->getPrefixedDBkey() .
220 " is a redirect, but it doesn't contain a valid redirect.\n" );
221 return false;
222 }
223 }
224
225 /**
226 * @param User $user
227 * @param string $reason
228 * @param bool $createRedirect
229 * @return Status
230 */
231 public function move( User $user, $reason, $createRedirect ) {
232 global $wgCategoryCollation;
233
234 Hooks::run( 'TitleMove', array( $this->oldTitle, $this->newTitle, $user ) );
235
236 // If it is a file, move it first.
237 // It is done before all other moving stuff is done because it's hard to revert.
238 $dbw = wfGetDB( DB_MASTER );
239 if ( $this->oldTitle->getNamespace() == NS_FILE ) {
240 $file = wfLocalFile( $this->oldTitle );
241 if ( $file->exists() ) {
242 $status = $file->move( $this->newTitle );
243 if ( !$status->isOk() ) {
244 return $status;
245 }
246 }
247 // Clear RepoGroup process cache
248 RepoGroup::singleton()->clearCache( $this->oldTitle );
249 RepoGroup::singleton()->clearCache( $this->newTitle ); # clear false negative cache
250 }
251
252 $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own.
253 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
254 $protected = $this->oldTitle->isProtected();
255
256 // Do the actual move
257 $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect );
258
259 // Refresh the sortkey for this row. Be careful to avoid resetting
260 // cl_timestamp, which may disturb time-based lists on some sites.
261 // @todo This block should be killed, it's duplicating code
262 // from LinksUpdate::getCategoryInsertions() and friends.
263 $prefixes = $dbw->select(
264 'categorylinks',
265 array( 'cl_sortkey_prefix', 'cl_to' ),
266 array( 'cl_from' => $pageid ),
267 __METHOD__
268 );
269 if ( $this->newTitle->getNamespace() == NS_CATEGORY ) {
270 $type = 'subcat';
271 } elseif ( $this->newTitle->getNamespace() == NS_FILE ) {
272 $type = 'file';
273 } else {
274 $type = 'page';
275 }
276 foreach ( $prefixes as $prefixRow ) {
277 $prefix = $prefixRow->cl_sortkey_prefix;
278 $catTo = $prefixRow->cl_to;
279 $dbw->update( 'categorylinks',
280 array(
281 'cl_sortkey' => Collation::singleton()->getSortKey(
282 $this->newTitle->getCategorySortkey( $prefix ) ),
283 'cl_collation' => $wgCategoryCollation,
284 'cl_type' => $type,
285 'cl_timestamp=cl_timestamp' ),
286 array(
287 'cl_from' => $pageid,
288 'cl_to' => $catTo ),
289 __METHOD__
290 );
291 }
292
293 $redirid = $this->oldTitle->getArticleID();
294
295 if ( $protected ) {
296 # Protect the redirect title as the title used to be...
297 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
298 array(
299 'pr_page' => $redirid,
300 'pr_type' => 'pr_type',
301 'pr_level' => 'pr_level',
302 'pr_cascade' => 'pr_cascade',
303 'pr_user' => 'pr_user',
304 'pr_expiry' => 'pr_expiry'
305 ),
306 array( 'pr_page' => $pageid ),
307 __METHOD__,
308 array( 'IGNORE' )
309 );
310 # Update the protection log
311 $log = new LogPage( 'protect' );
312 $comment = wfMessage(
313 'prot_1movedto2',
314 $this->oldTitle->getPrefixedText(),
315 $this->newTitle->getPrefixedText()
316 )->inContentLanguage()->text();
317 if ( $reason ) {
318 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
319 }
320 // @todo FIXME: $params?
321 $logId = $log->addEntry(
322 'move_prot',
323 $this->newTitle,
324 $comment,
325 array( $this->oldTitle->getPrefixedText() ),
326 $user
327 );
328
329 // reread inserted pr_ids for log relation
330 $insertedPrIds = $dbw->select(
331 'page_restrictions',
332 'pr_id',
333 array( 'pr_page' => $redirid ),
334 __METHOD__
335 );
336 $logRelationsValues = array();
337 foreach ( $insertedPrIds as $prid ) {
338 $logRelationsValues[] = $prid->pr_id;
339 }
340 $log->addRelations( 'pr_id', $logRelationsValues, $logId );
341 }
342
343 // Update *_from_namespace fields as needed
344 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
345 $dbw->update( 'pagelinks',
346 array( 'pl_from_namespace' => $this->newTitle->getNamespace() ),
347 array( 'pl_from' => $pageid ),
348 __METHOD__
349 );
350 $dbw->update( 'templatelinks',
351 array( 'tl_from_namespace' => $this->newTitle->getNamespace() ),
352 array( 'tl_from' => $pageid ),
353 __METHOD__
354 );
355 $dbw->update( 'imagelinks',
356 array( 'il_from_namespace' => $this->newTitle->getNamespace() ),
357 array( 'il_from' => $pageid ),
358 __METHOD__
359 );
360 }
361
362 # Update watchlists
363 $oldtitle = $this->oldTitle->getDBkey();
364 $newtitle = $this->newTitle->getDBkey();
365 $oldsnamespace = MWNamespace::getSubject( $this->oldTitle->getNamespace() );
366 $newsnamespace = MWNamespace::getSubject( $this->newTitle->getNamespace() );
367 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
368 WatchedItem::duplicateEntries( $this->oldTitle, $this->newTitle );
369 }
370
371 $dbw->commit( __METHOD__ );
372
373 Hooks::run(
374 'TitleMoveComplete',
375 array( &$this->oldTitle, &$this->newTitle, &$user, $pageid, $redirid, $reason )
376 );
377 return Status::newGood();
378 }
379
380 /**
381 * Move page to a title which is either a redirect to the
382 * source page or nonexistent
383 *
384 * @fixme This was basically directly moved from Title, it should be split into smaller functions
385 * @param User $user the User doing the move
386 * @param Title $nt The page to move to, which should be a redirect or nonexistent
387 * @param string $reason The reason for the move
388 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
389 * if the user has the suppressredirect right
390 * @throws MWException
391 */
392 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true ) {
393 global $wgContLang;
394
395 if ( $nt->exists() ) {
396 $moveOverRedirect = true;
397 $logType = 'move_redir';
398 } else {
399 $moveOverRedirect = false;
400 $logType = 'move';
401 }
402
403 if ( $createRedirect ) {
404 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
405 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
406 ) {
407 $redirectContent = new WikitextContent(
408 wfMessage( 'category-move-redirect-override' )
409 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
410 } else {
411 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
412 $redirectContent = $contentHandler->makeRedirectContent( $nt,
413 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
414 }
415
416 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
417 } else {
418 $redirectContent = null;
419 }
420
421 // bug 57084: log_page should be the ID of the *moved* page
422 $oldid = $this->oldTitle->getArticleID();
423 $logTitle = clone $this->oldTitle;
424
425 $logEntry = new ManualLogEntry( 'move', $logType );
426 $logEntry->setPerformer( $user );
427 $logEntry->setTarget( $logTitle );
428 $logEntry->setComment( $reason );
429 $logEntry->setParameters( array(
430 '4::target' => $nt->getPrefixedText(),
431 '5::noredir' => $redirectContent ? '0': '1',
432 ) );
433
434 $formatter = LogFormatter::newFromEntry( $logEntry );
435 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
436 $comment = $formatter->getPlainActionText();
437 if ( $reason ) {
438 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
439 }
440 # Truncate for whole multibyte characters.
441 $comment = $wgContLang->truncate( $comment, 255 );
442
443 $dbw = wfGetDB( DB_MASTER );
444
445 $oldpage = WikiPage::factory( $this->oldTitle );
446 $oldcountable = $oldpage->isCountable();
447
448 $newpage = WikiPage::factory( $nt );
449
450 if ( $moveOverRedirect ) {
451 $newid = $nt->getArticleID();
452 $newcontent = $newpage->getContent();
453
454 # Delete the old redirect. We don't save it to history since
455 # by definition if we've got here it's rather uninteresting.
456 # We have to remove it so that the next step doesn't trigger
457 # a conflict on the unique namespace+title index...
458 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
459
460 $newpage->doDeleteUpdates( $newid, $newcontent );
461 }
462
463 # Save a null revision in the page's history notifying of the move
464 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
465 if ( !is_object( $nullRevision ) ) {
466 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
467 }
468
469 $nullRevision->insertOn( $dbw );
470
471 # Change the name of the target page:
472 $dbw->update( 'page',
473 /* SET */ array(
474 'page_namespace' => $nt->getNamespace(),
475 'page_title' => $nt->getDBkey(),
476 ),
477 /* WHERE */ array( 'page_id' => $oldid ),
478 __METHOD__
479 );
480
481 // clean up the old title before reset article id - bug 45348
482 if ( !$redirectContent ) {
483 WikiPage::onArticleDelete( $this->oldTitle );
484 }
485
486 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
487 $nt->resetArticleID( $oldid );
488 $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397
489
490 $newpage->updateRevisionOn( $dbw, $nullRevision );
491
492 Hooks::run( 'NewRevisionFromEditComplete',
493 array( $newpage, $nullRevision, $nullRevision->getParentId(), $user ) );
494
495 $newpage->doEditUpdates( $nullRevision, $user,
496 array( 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ) );
497
498 if ( !$moveOverRedirect ) {
499 WikiPage::onArticleCreate( $nt );
500 }
501
502 # Recreate the redirect, this time in the other direction.
503 if ( $redirectContent ) {
504 $redirectArticle = WikiPage::factory( $this->oldTitle );
505 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397
506 $newid = $redirectArticle->insertOn( $dbw );
507 if ( $newid ) { // sanity
508 $this->oldTitle->resetArticleID( $newid );
509 $redirectRevision = new Revision( array(
510 'title' => $this->oldTitle, // for determining the default content model
511 'page' => $newid,
512 'user_text' => $user->getName(),
513 'user' => $user->getId(),
514 'comment' => $comment,
515 'content' => $redirectContent ) );
516 $redirectRevision->insertOn( $dbw );
517 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
518
519 Hooks::run( 'NewRevisionFromEditComplete',
520 array( $redirectArticle, $redirectRevision, false, $user ) );
521
522 $redirectArticle->doEditUpdates( $redirectRevision, $user, array( 'created' => true ) );
523 }
524 }
525
526 # Log the move
527 $logid = $logEntry->insert();
528 $logEntry->publish( $logid );
529 }
530 }