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 # Update the protection log
309 $log = new LogPage( 'protect' );
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 // @todo FIXME: $params?
319 $logId = $log->addEntry(
320 'move_prot',
321 $this->newTitle,
322 $comment,
323 array( $this->oldTitle->getPrefixedText() ),
324 $user
325 );
326
327 // reread inserted pr_ids for log relation
328 $insertedPrIds = $dbw->select(
329 'page_restrictions',
330 'pr_id',
331 array( 'pr_page' => $redirid ),
332 __METHOD__
333 );
334 $logRelationsValues = array();
335 foreach ( $insertedPrIds as $prid ) {
336 $logRelationsValues[] = $prid->pr_id;
337 }
338 $log->addRelations( 'pr_id', $logRelationsValues, $logId );
339 }
340
341 // Update *_from_namespace fields as needed
342 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
343 $dbw->update( 'pagelinks',
344 array( 'pl_from_namespace' => $this->newTitle->getNamespace() ),
345 array( 'pl_from' => $pageid ),
346 __METHOD__
347 );
348 $dbw->update( 'templatelinks',
349 array( 'tl_from_namespace' => $this->newTitle->getNamespace() ),
350 array( 'tl_from' => $pageid ),
351 __METHOD__
352 );
353 $dbw->update( 'imagelinks',
354 array( 'il_from_namespace' => $this->newTitle->getNamespace() ),
355 array( 'il_from' => $pageid ),
356 __METHOD__
357 );
358 }
359
360 # Update watchlists
361 $oldtitle = $this->oldTitle->getDBkey();
362 $newtitle = $this->newTitle->getDBkey();
363 $oldsnamespace = MWNamespace::getSubject( $this->oldTitle->getNamespace() );
364 $newsnamespace = MWNamespace::getSubject( $this->newTitle->getNamespace() );
365 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
366 WatchedItem::duplicateEntries( $this->oldTitle, $this->newTitle );
367 }
368
369 $dbw->commit( __METHOD__ );
370
371 Hooks::run(
372 'TitleMoveComplete',
373 array( &$this->oldTitle, &$this->newTitle, &$user, $pageid, $redirid, $reason )
374 );
375 return Status::newGood();
376 }
377
378 /**
379 * Move page to a title which is either a redirect to the
380 * source page or nonexistent
381 *
382 * @fixme This was basically directly moved from Title, it should be split into smaller functions
383 * @param User $user the User doing the move
384 * @param Title $nt The page to move to, which should be a redirect or nonexistent
385 * @param string $reason The reason for the move
386 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
387 * if the user has the suppressredirect right
388 * @throws MWException
389 */
390 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true ) {
391 global $wgContLang;
392
393 if ( $nt->exists() ) {
394 $moveOverRedirect = true;
395 $logType = 'move_redir';
396 } else {
397 $moveOverRedirect = false;
398 $logType = 'move';
399 }
400
401 if ( $createRedirect ) {
402 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
403 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
404 ) {
405 $redirectContent = new WikitextContent(
406 wfMessage( 'category-move-redirect-override' )
407 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
408 } else {
409 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
410 $redirectContent = $contentHandler->makeRedirectContent( $nt,
411 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
412 }
413
414 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
415 } else {
416 $redirectContent = null;
417 }
418
419 // bug 57084: log_page should be the ID of the *moved* page
420 $oldid = $this->oldTitle->getArticleID();
421 $logTitle = clone $this->oldTitle;
422
423 $logEntry = new ManualLogEntry( 'move', $logType );
424 $logEntry->setPerformer( $user );
425 $logEntry->setTarget( $logTitle );
426 $logEntry->setComment( $reason );
427 $logEntry->setParameters( array(
428 '4::target' => $nt->getPrefixedText(),
429 '5::noredir' => $redirectContent ? '0': '1',
430 ) );
431
432 $formatter = LogFormatter::newFromEntry( $logEntry );
433 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
434 $comment = $formatter->getPlainActionText();
435 if ( $reason ) {
436 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
437 }
438 # Truncate for whole multibyte characters.
439 $comment = $wgContLang->truncate( $comment, 255 );
440
441 $dbw = wfGetDB( DB_MASTER );
442
443 $oldpage = WikiPage::factory( $this->oldTitle );
444 $oldcountable = $oldpage->isCountable();
445
446 $newpage = WikiPage::factory( $nt );
447
448 if ( $moveOverRedirect ) {
449 $newid = $nt->getArticleID();
450 $newcontent = $newpage->getContent();
451
452 # Delete the old redirect. We don't save it to history since
453 # by definition if we've got here it's rather uninteresting.
454 # We have to remove it so that the next step doesn't trigger
455 # a conflict on the unique namespace+title index...
456 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
457
458 $newpage->doDeleteUpdates( $newid, $newcontent );
459 }
460
461 # Save a null revision in the page's history notifying of the move
462 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
463 if ( !is_object( $nullRevision ) ) {
464 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
465 }
466
467 $nullRevision->insertOn( $dbw );
468
469 # Change the name of the target page:
470 $dbw->update( 'page',
471 /* SET */ array(
472 'page_namespace' => $nt->getNamespace(),
473 'page_title' => $nt->getDBkey(),
474 ),
475 /* WHERE */ array( 'page_id' => $oldid ),
476 __METHOD__
477 );
478
479 // clean up the old title before reset article id - bug 45348
480 if ( !$redirectContent ) {
481 WikiPage::onArticleDelete( $this->oldTitle );
482 }
483
484 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
485 $nt->resetArticleID( $oldid );
486 $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397
487
488 $newpage->updateRevisionOn( $dbw, $nullRevision );
489
490 Hooks::run( 'NewRevisionFromEditComplete',
491 array( $newpage, $nullRevision, $nullRevision->getParentId(), $user ) );
492
493 $newpage->doEditUpdates( $nullRevision, $user,
494 array( 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ) );
495
496 if ( !$moveOverRedirect ) {
497 WikiPage::onArticleCreate( $nt );
498 }
499
500 # Recreate the redirect, this time in the other direction.
501 if ( $redirectContent ) {
502 $redirectArticle = WikiPage::factory( $this->oldTitle );
503 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397
504 $newid = $redirectArticle->insertOn( $dbw );
505 if ( $newid ) { // sanity
506 $this->oldTitle->resetArticleID( $newid );
507 $redirectRevision = new Revision( array(
508 'title' => $this->oldTitle, // for determining the default content model
509 'page' => $newid,
510 'user_text' => $user->getName(),
511 'user' => $user->getId(),
512 'comment' => $comment,
513 'content' => $redirectContent ) );
514 $redirectRevision->insertOn( $dbw );
515 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
516
517 Hooks::run( 'NewRevisionFromEditComplete',
518 array( $redirectArticle, $redirectRevision, false, $user ) );
519
520 $redirectArticle->doEditUpdates( $redirectRevision, $user, array( 'created' => true ) );
521 }
522 }
523
524 # Log the move
525 $logid = $logEntry->insert();
526 $logEntry->publish( $logid );
527 }
528 }