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